简体   繁体   中英

How to remove elements in a drop down inside a div element using JavaScript

I want to remove elements in a dropdown, the example of the HTML code is below and I need to select elements by div class "woo-vpf-field-make" then select the name "make" and then option value "73483".

I hope that makes sense:)

<div class="woo-vpf-field-make">
  <select name="make">
    <option value="">Select Make</option>
    <option value="70281">BMW</option>
    <option value="73483">Fiat</option>
    <option value="73923">Ford</option>
    <option value="71367">Mini</option>
    <option value="75988">Opel / Vauxhall</option>
    <option value="74715">Volkswagen</option>                   
  </select>
</div>

Below is the JavaScript code that I wrote, but seems like it could be lot better:)

$(document).ready(function() {
    $('select[name^="make"]').children("option[value^=" + "73483" + "]").remove();
    $('select[name^="make"]').children("option[value^=" + "73923" + "]").remove();
    $('select[name^="make"]').children("option[value^=" + "75988" + "]").remove();
    $('select[name^="make"]').children("option[value^=" + "74715" + "]").remove();
})

You could add option value in array.And remove the element using forEach based on array value

 var r_arr = ["73483", "73923", "75988", "74715"]; $(document).ready(function() { r_arr.forEach(function(value) { $('select[name^="make"]').find("option[value^=" +value+ "]").remove(); }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="woo-vpf-field-make"> <select name="make"> <option value="">Select Make</option> <option value="70281">BMW</option> <option value="73483">Fiat</option> <option value="73923">Ford</option> <option value="71367">Mini</option> <option value="75988">Opel / Vauxhall</option> <option value="74715">Volkswagen</option> </select> </div>

Assign an id to your dropdown

$("#select_id option[value='73483']").remove();

Just use the find() function to search your value that remove it

$('select[name^="make"]').find("option[value^=" +value+ "]").remove();

or You can assign a Id to your select than it will be more easy to find

$("#id option[value=" +value+ "]").remove();

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