Friday, September 23, 2011

jQuery: Selecting Elements by Value

If you are familiar with jQuery's selectors, then you've probably seen examples like:
$('input[title="something"]').val()
If that doesn't look familiar, the above code will select the first occurrence of input element with a title of "something" and return its value. As a note, omitting the .val() will return an array of elements matching our selector.

This is pretty straightforward, but you can select an element by its value using the following.
$('input[value="something"]')

The one that throws some people is selecting a Select element by its value. To do that, use the following:
$('select option:selected[value="something"]')
Or, if you want to search based on the text of the 'option' element:
$('select option:selected[text="something"]')

Hopefully this saves somebody some time.

No comments:

Post a Comment