so apparently you have the following
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
but what if you have
<select>
<option value="0">1</option>
<option value="1">0</option>
</select>
And I want to set the value...of the form...how can I tell jquery to specifically use the value field or specifically the text in between the option tag...
so apparently you have the following
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
but what if you have
<select>
<option value="0">1</option>
<option value="1">0</option>
</select>
And I want to set the value...of the form...how can I tell jquery to specifically use the value field or specifically the text in between the option tag...
Share Improve this question asked Mar 28, 2012 at 20:45 pillarOfLightpillarOfLight 9,01216 gold badges61 silver badges91 bronze badges 4- Hint: you don't set the value, you set the selectedIndex. – Diodeus - James MacFarlane Commented Mar 28, 2012 at 20:49
- It doesn't: jsfiddle/Z9ySD. – pimvdb Commented Mar 28, 2012 at 20:50
- @pimvdb - Actually this seems to work if you remove the values from the option elements. jQuery's .val() page actually uses an example like this, although I wouldn't remend doing this. – j08691 Commented Mar 28, 2012 at 20:53
- @j08691: You're correct. Though the OP's confusion doesn't apply in that case. – pimvdb Commented Mar 28, 2012 at 20:57
3 Answers
Reset to default 3$('select').find('option[value="1"]').attr('selected', true );
Just select the option
based on the value (with the attribute selector) and set the selected attribute like this:
var value = "1"; // Set the value that you want to select
$("select option[value=" + value + "]").attr("selected","selected");
http://jsfiddle/VU9BC/
Just select the option based on the value (with the attribute selector) and set the selected attribute like this Simply no Headace :)
By Value
$( "select" ).change( displayVals );
https://jsfiddle/haroonmind/quemz47o/1/