Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector for <select>'s <option> box

Given the HTML below, I need a jQuery selector that selects the <option> with the with-stamp class.

<select name="preset_select">
    <option selected="selected" value="original">ORIGINAL</option>
    <option value="large">LARGE</option>
    <option class="with-stamp" value="medium">MEDIUM</option>
</select>

$("select[name=preset_select]").change(function() {
    // console.log( $(this).hasClass("with-stamp") ); // all false
    // console.log( $("select[name=preset_select] option").hasClass("with-stamp") ); // all true
});
like image 778
FFish Avatar asked Nov 23 '10 23:11

FFish


People also ask

How do you select a particular option in a select element in jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).

What do the jQuery selectors in this code select?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more.

Can you use CSS selectors in jQuery for selecting elements?

Projects In JavaScript & JQueryjQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element.


3 Answers

$("select[name='preset_select']").change(function() {
    $(this).children(':selected').hasClass('with-timestamp')
}
like image 193
PeeHaa Avatar answered Oct 14 '22 05:10

PeeHaa


You need to check only the :selected <option> (since .hasClass() returns true if any of the elements in the set have the class), like this:

$("select[name=preset_select] option:selected").hasClass("with-stamp")
like image 22
Nick Craver Avatar answered Oct 14 '22 04:10

Nick Craver


$("select[name=preset_select] option:selected").hasClass('with-stamp').change(function() { 

}); 
like image 24
Ali Tarhini Avatar answered Oct 14 '22 04:10

Ali Tarhini