Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a select option by a value passed through a variable

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 ?

like image 661
Ilyes Ferchiou Avatar asked Jun 30 '12 19:06

Ilyes Ferchiou


2 Answers

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);
like image 118
gdoron is supporting Monica Avatar answered Nov 15 '22 07:11

gdoron is supporting Monica


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.

like image 20
Mark Eirich Avatar answered Nov 15 '22 07:11

Mark Eirich