emilly
emilly

Reputation: 10530

How to check whether selectbox contains any option with specific class?

In jQuery, how can I check that a selectbox contains a specific class or not? For example, in the below code snippet, I want to check whether the selectbox with id "customerIds" contains any option with class "C" or "D".

<select id="customerIds" onchange="doOperation()">
    <option value="default"> Start..</option>
    <option value="1" class="A"> 1</option>
    <option value="2" class="B"> 2</option>
    <option value="3" class="C"> 3 </option>
</select>

Upvotes: 0

Views: 271

Answers (4)

Alexander
Alexander

Reputation: 23537

For instance you can use :has.

var hasOption = !!$("#customerIds:has(option.C,option.D)").length;

Or .children() as well, which may prove to be faster.

var hasOption = !!$("#customerIds").children("option.C,option.D").length;

var hasOption = !!$("#customerIds > option.C,option.D").length;

Upvotes: 1

Frederik.L
Frederik.L

Reputation: 5620

What about :

if ($('#customerIds > .C').length > 0 || $('#customerIds > .D').length > 0) {
    // ...
}

OR a more flexible/optimizable one

var selectBox = $('#customerIds');

if (selectBox.find('.C').length > 0 || selectBox.find('.D').length > 0) {
    // ...
}

Upvotes: 0

kamil
kamil

Reputation: 3522

Use hasClass() method: http://api.jquery.com/hasClass/

For example:

$("#customerIds").find("option").hasClass("A");

Upvotes: 1

Sang Suantak
Sang Suantak

Reputation: 5265

You can do:

if($("#customerIds option[class='C']").length > 0) {
    //do something
}

Upvotes: 0

Related Questions