user3130287
user3130287

Reputation:

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();
})

Upvotes: 0

Views: 126

Answers (3)

Mannu saraswat
Mannu saraswat

Reputation: 1081

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();

Upvotes: 0

prasanth
prasanth

Reputation: 22500

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>

Upvotes: 1

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

Assign an id to your dropdown

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

Upvotes: 0

Related Questions