I have an html file that contains the following code :
<select id="gouv" name="gouv">
...some options here...
</select>
and the following jQuery code :
$('#gouv option[value="myvalue"]').attr("checked","checked");
this as you certainly know sets the option with the value "myvalue" to checked which works perfectly.
Now the problem is, I don't know the value of the option I want to set as checked because this value is a result of some function which is stored within a global variable. For simplification sake, after long debugging, I reduced the problem to the following :
var ident="myvalue";
$('#gouv option[value=ident]').attr("checked","checked");
and this code doesn't work !
I would like to know why it doesn't work, can't we pass a value as a variable ? And is there any workaround to this ?
var ident="myvalue";
$('#gouv option[value="' + ident + '"]').attr("selected", "selected");
selected
is for <option>
, checked
is for radio!
And better use prop
if your jQuery version is > 1.6
$('#gouv option[value="' + ident +'"]').prop("selected", true);
Note that you better use filter
instead of attribute selector:
$('#gouv option').filter(function(){
return this.value == indent;
}).prop("selected", true);
Why you should use filter
for value
If you need to support blackberry, they have bug with option.value that jQuery handle:
$('#gouv option').filter(function(){
return $(this).val() == indent;
}).prop("selected", true);
jQuery's .val()
(see here) will select an option by value:
var ident = "myvalue";
$('#gouv').val(ident);
This is equivalent to:
var ident = "myvalue";
$('#gouv option[value="' + ident + '"]').attr("selected", "selected");
Except that the latter will have issues if ident
contains any double quotes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With