Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...)

like image 608
grimmwerks Avatar asked Oct 20 '22 01:10

grimmwerks


2 Answers

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>
like image 190
Arun P Johny Avatar answered Oct 23 '22 04:10

Arun P Johny


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();
like image 44
Bhushan Kawadkar Avatar answered Oct 23 '22 02:10

Bhushan Kawadkar