简体   繁体   中英

How to select <select> elements with no html in them through JQuery

I have following html select elements

    <select  id="options1" title="prd_name" name="options">
       <option value="optiona">Option A</option>
       <option value="optionb">Option B</option>
       <option value="optionc">Option C</option>
    </select>
    <select  id="options2" title="prd_name" name="options"> </select>
    <select  id="options3" title="prd_name" name="options"> </select>
    <select  id="options4" title="prd_name" name="options"> </select>

Only the first select element with id="options1" has option tags in it, the rest of select elements are empty. I want to select those empty select elements so that I be able to populate options into them, without touching the first select element which already has options into it. How can I do this especially through Jquery?

You can use selector select:empty ; alternatively you can use select:not(:has(option))

 console.log($("select:empty")); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <select id="options1" title="prd_name" name="options"> <option value="optiona">Option A</option> <option value="optionb">Option B</option> <option value="optionc">Option C</option> </select> <select id="options2" title="prd_name" name="options"></select> <select id="options3" title="prd_name" name="options"></select> <select id="options4" title="prd_name" name="options"></select> 

try this

var $select = $("select").filter(function () {
         return !$(this).find("option").length;
       });
console.log($select);

$select will give you all the select boxes except the with option elements then you can loop over $select and perform any task on it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM