Selecting a select option by a value passed through a variable

38,407

Solution 1

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);

Solution 2

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.

Share:
38,407
Ilyes Ferchiou
Author by

Ilyes Ferchiou

I'm a mechanical engineer, a graphic designer and a website designer. I work as a freelancer.

Updated on July 23, 2022

Comments

  • Ilyes Ferchiou
    Ilyes Ferchiou almost 2 years

    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 ?