Jquery: [] selector?

For a SELECT element:

<select> <option>foo</option> <option>bar</option> <option>baz</option> </select> 

I want to select an OPTION element with a value of "bar".

This does not work:

 $('option[text="bar"]').attr('selected', true); 

However, this works:

 $('option:[text="bar"]').attr('selected', true); 

Why?

Live demo: http://jsfiddle.net/YbfqZ/2/

+7
source share
2 answers

The reason for this behavior is that your colon breaks the selector into querySelectorAll because it is not valid.

As such, it by default uses Sizzle, which will tolerate the colon, even if it is not technically supported (which means that it may break in the future). Sizzle will check both attributes and properties. Thus, it will not find the text attribute, but it will find the text property of the <option> element.

Here is an example that demonstrates that Sizzle will match a property, not just an attribute with its attribute-equals selector.


Code from the 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 referred to another example because I dialed the wrong version number. Fixed.

+8
source

The proper way to do this is to give a SELECT id and provide the values ​​of the OPTION elements. Then you can set the selection value.

 <select id="theSelect"> <option value="foo">foo</option> <option value="bar">bar</option> <option value="baz">baz</option> </select> 

And JS will look like this:

 $('#theSelect').val('foo'); 

Live Demo http://jsfiddle.net/YbfqZ/4/

+2
source

All Articles