grimmwerks
grimmwerks

Reputation: 491

jquery - finding the first select that has the first value selected?

I've got a number of select dropdowns, and the first value of all is empty (ie ""). What is the best way of selecting the FIRST select whose value is ""? I've been trying things like

$j("[id*='user'] option[value='']").first().prop("selected", true);

But that's setting it vs looking for one that matches.

(ALL the ids start with 'user'; I need to find the first user select that has an empty value...)

Upvotes: 5

Views: 85

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388446

Since you want the select element, you can try .has()

$j("[id*='user']").has('option[value=""]:selected').first()

Try

$("[id*='user']").has('option[value=""]:selected').first().css({
    "color": 'red',
    "border-color": 'green'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="user-1">
  <option value="">Select</option>
  <option selected="selected">1</option>
</select>
<select id="user-2">
  <option value="">Select</option>
  <option selected="selected">1</option>
</select>
<select id="user-3">
  <option value="">Select</option>
  <option>1</option>
</select>
<select id="user-4">
  <option value="">Select</option>
  <option>1</option>
</select>
<select id="user-5">
  <option value="">Select</option>
  <option selected="selected">1</option>
</select>

Upvotes: 2

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

You need to use start with jquery selector i.e. [id^=startwithid] to get all ids start with user, see below code

$j("[id^='user'] option[value=]:selected").first().parent();

Or best way to use :has like below

$j("[id^='user']:has(option[value=]:selected)").first();

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82251

You can use :has selector to find select having option value "" as selected:

$j("[id*='user']:has(option[value='']:selected)").first();

or

$j("[id*='user']:has(option[value='']:selected):eq(0)");

Upvotes: 0

Related Questions