...">

Choosing a selection option by the value passed to the variable

I have an html file containing 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 a parameter with a value of "myvalue" for validation, which works fine.

Now the problem is that I do not know the value of the parameter that I want to set as set, because this value is the result of some function that is stored in a global variable. To simplify, after a long debugging, I reduced the problem to the following:

 var ident="myvalue"; $('#gouv option[value=ident]').attr("checked","checked"); 

and this code does not work!

I would like to know why this does not work, is it possible to pass the value as a variable? And is there any workaround?

+4
source share
2 answers
 var ident="myvalue"; $('#gouv option[value="' + ident + '"]').attr("selected", "selected"); 

selected for <option> , checked for radio!

And it's better to use prop if your jQuery version> 1.6

 $('#gouv option[value="' + ident +'"]').prop("selected", true); 

Please note that instead of the attribute selector it is better to use filter :

 $('#gouv option').filter(function(){ return this.value == indent; }).prop("selected", true); 

Why you should use filter for value

If you need to support a blackberry, they have a parameter error. value that jQuery processes:

 $('#gouv option').filter(function(){ return $(this).val() == indent; }).prop("selected", true); 
+15
source

jQuery .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 problems if ident contains any double quotes.

+4
source

All Articles