Looking for the first choice that selects the first value?

I have a number of dropdown menus, and the first value for all is empty (i.e., "). What is the best way to select FIRST, whose value is" "? I tried things like

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

But that means that he is looking for one that matches.

(ALL IDs start with "user", I need to find the first user selection that has an empty value ...)

+5
source share
3 answers

Since you need a 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> 
+2
source

You need to use start with jquery selector ie [id^=startwithid] so that all IDs start with user, see below code

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

Or a better way to use :has , as shown below

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

You can use the :has selector to select an option that has the value of the "" option, as selected:

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

or

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

Source: https://habr.com/ru/post/1202750/


All Articles