Skip to content

Instantly share code, notes, and snippets.

@thisisbrians
Created February 3, 2013 00:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thisisbrians/4699851 to your computer and use it in GitHub Desktop.
Save thisisbrians/4699851 to your computer and use it in GitHub Desktop.
Dynamically select a timezone in a Rails time_zone_select based on the browser's timezone using jQuery/JavaScript.
jQuery.fn.selectTimeZone = function() {
var $el = $(this[0]); // our element
var offsetFromGMT = String(- new Date('1/1/2009').getTimezoneOffset() / 60); // using 1/1/2009 so we know DST isn't tripping us up
if (offsetFromGMT[0] != '-') {
offsetFromGMT = '+' + offsetFromGMT; // if it's not negative, prepend a +
}
if (offsetFromGMT.length < 3) {
offsetFromGMT = offsetFromGMT.substr(0, 1) + '0' + offsetFromGMT.substr(1); // add a leading zero if we need it
}
var regEx = new RegExp(offsetFromGMT); // create a RegExp object with our pattern
$('option', $el).each(function(index, option) { // loop through all the options in our element
var $option = $(option); // cache a jQuery object for the option
if($option.html().match(regEx)) { // check if our regex matches the html(text) inside the option
$option.attr({selected: 'true'}); // select the option
return false; // stop the loop—we're all done here
}
});
}
$('#time-zone-select').selectTimeZone(); // invoke our function on the time zone select menu
@ayb
Copy link

ayb commented May 20, 2016

Thanks for sharing this.

For what it's worth, I had some issues with iPhone Mobile Safari (iOS 9.3-ish) not always setting the time zone field properly (even when it identified the timezone and had the right regexp etc.)

So I ended up changing the line $option.attr({selected: 'true'}); to $option.prop('selected', true); and it began working a lot more consistently for me.

Your mileage may vary, but it was the solution to my frustration :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment