Given a SELECT element:
<select>
<option>foo</option>
<option>bar</option>
<option>baz</option>
</select>
I want to select the OPTION element with the value "bar".
This doesn't work:
$('option[text="bar"]').attr('selected', true);
However, this does work:
$('option:[text="bar"]').attr('selected', true);
Why?
Live demo: http://jsfiddle.net/YbfqZ/2/
The reason for that behavior is that your colon breaks the selector for querySelectorAll
because it isn't valid.
As such, it defaults to Sizzle, which will tolerate the colon, even though it technically isn't supported (which means it could break in the future). Sizzle will check for both attributes and properties. As such, it won't find a text
attribute, but it will find the text
property of the <option>
element.
Here's an example that demonstrates that Sizzle will match a property instead of just an attribute with its attribute-equals
selector.
Code from example:
// set a custom property on the last option
$('#id option').slice(-1)[0].customProp = 'customValue';
// breaking the selector with : we default to Sizzle,
// which matches our custom property
$('#id option:[customProp="customValue"]').attr('selected', true);
EDIT: My example link previously referenced someone else's example because I typed the wrong revision number. Fixed.
The correct way to do this is to give the SELECT an id, and give the OPTION items values. Then you can set the select's value.
<select id="theSelect">
<option value="foo">foo</option>
<option value="bar">bar</option>
<option value="baz">baz</option>
</select>
And the JS would look like this
$('#theSelect').val('foo');
Live Demo http://jsfiddle.net/YbfqZ/4/
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