I am trying to add "selected" option in select list of html when it matches user timezone,
Here is my try :- http://jsfiddle.net/HYfQ5/
I am not Javascript / jquery Student :'(
HTML List :-
<select name="timezone" id="timezone" required>
<option value="Africa/Abidjan" > Africa/Abidjan</option>
<option value="Africa/Accra" > Africa/Accra</option>
<option value="Africa/Addis_Ababa" > Africa/Addis_Ababa</option>
....... <!--Rest Item is in Above Link, Don't want to fill this place with 480 items -->
</select>
and my Jquery modification :-
<script type="text/javascript" src="http://cdn.bitbucket.org/pellepim/jstimezonedetect/downloads/jstz-1.0.4.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var tz = jstz.determine();
var timez = new Array();
var timez = $('#timezone').val();
response_text = 'No timezone found';
if (typeof (tz) === 'undefined') {
response_text = 'No timezone found';
}
else {
response_text = tz.name();
}
for(var i=0;i<array.length;i++) {
if (timez[i] === response_text) {
$('#timezone').attr('selected')
}
}
});
</script>
So, Whenever it matches the user timezone, it should automatically append "selected" value to select list.
Javascript timezone, i am using :- http://pellepim.bitbucket.org/jstz/
Thanks!
there is a little bug in your function. use this code:
$("#timezone option").each(function(){
if($(this).val() == response_text){
$(this).attr('selected','selected');
}
})
Instead of this:
for(var i=0;i<array.length;i++) {
if (timez[i] === response_text) {
$('#timezone').attr('selected')
}
}
working code here: http://jsfiddle.net/HYfQ5/1/
You can try this: http://jsfiddle.net/HYfQ5/2/
Calling val() on a select will select the option with that value, if any.
I have made following changes to the code:
var timez = $('#timezone');
and replaced the for loop by:
timez.val(response_text);
When you set .val() to a select list it will select the option with that value.
$(document).ready(function () {
var tz = jstz.determine();
response_text = 'No timezone found';
if (typeof (tz) === 'undefined') {
response_text = 'No timezone found';
}
else {
response_text = tz.name();
}
$('#timezone').val(response_text);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.