Kicker
Kicker

Reputation: 606

jQuery check if selects have options

I have a random count of selects on page with the same class e.g. .selectWidth and I need to check which select has not any options and for each select with no options do same function.

Upvotes: 1

Views: 31

Answers (2)

Joseph Marikle
Joseph Marikle

Reputation: 78520

You can use .filter()

jQuery

$('.selectWidth').filter(function(){
    return this.options.length === 0;
}).each(function(){
    // do something
});

HTML

<select class="selectWidth"></select>
<select class="selectWidth">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>
<select class="selectWidth">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>
<select class="selectWidth"></select>
<select class="selectWidth"></select>

Upvotes: 1

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You can select which has no option like following.

$('.selectWidth:not(:has(option))')

You can iterate through these using each like below.

$('.selectWidth:not(:has(option))').each(function() {
    // do you stuff
})

Upvotes: 1

Related Questions