Created
February 3, 2013 00:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)