I am having a dropdown. When the page loads I want to select the option based on the value.
I have a hash which contains id as key and some number as its value. I am looping through this hash and if any of the option's value matches the current loop's value I need to set that option as selected.
$.each(hash_name_here, function(key, value){
$('select option[value=key]').attr("selected',"selected");
});
This does nothing.
But if I substitute the number instead of key it works fine.
$('select option[value=81]').attr("selected',"selected");
What am I doing wrong?
You have to let Jquery know that key is a variable. Now it's parsed as a string. Use:
$.each(hash_name_here, function(key, value){
$('select option[value=' + key + ']').attr("selected","selected");
});
Try this
$.each(hash_name_here, function(key, value){
$('#key option[value=value]').prop("selected",true);
});
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.