Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery :[] selector?

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/

like image 730
Šime Vidas Avatar asked Feb 15 '11 21:02

Šime Vidas


2 Answers

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.

like image 122
user113716 Avatar answered Sep 21 '22 20:09

user113716


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/

like image 29
Dutchie432 Avatar answered Sep 17 '22 20:09

Dutchie432