0

Suppose I have a Select element:

<select> <option value="Name 1">Simon</option> <option value="Name 2">Frank</option> <option value="Name 3">Bob</option> <option value="Name 4">Alex</option> </select> 

And I have an array of strings, suppose:

["Simon", "Alex"] 

How do I remove from the DOM (using jQuery) every option element that does not have a inner html value contained in the above list? For example, given the above list of inner html values (["Simon", "Alex"]), I would like to remove only the <option value="Name 2">Frank</option> and <option value="Name 3">Bob</option> elements, so that the final select element would look like:

<select> <option value="Name 1">Simon</option> <option value="Name 4">Alex</option> </select> 

2 Answers 2

7

Try this:

var list = ["Simon", "Alex"]; // Say your list is this $(function(){ $('select option').filter(function () { //Use filter on options return $.inArray(this.innerHTML, list) == -1 // get the option text which is not in the array }).remove(); //Remove them }); 

Demo

Refer

Meanwhile instead of $.inArray you can also use ecmascript-5 spec Array.prototype.indexOf

return list.indexOf(this.innerHTML) == -1

Sign up to request clarification or add additional context in comments.

Comments

2

Another way is to clear the Select and re-populate it using array or JSON formatted data structure:

// JSON formatted data structure list = { "1": "Simon", "2" : "Alex" }; // Removes all options for the select box $('select option').remove(); // Add option to the select box from list $.each(list, function(key, value) { $('select') .append($("<option></option>") .attr("value",key) .text(value)); }); 

Above example is using JSON fromat (which I recommend as it's always faster than Arrays). If you still want to use Array just replace the JSON list with your array list (i.e. var list = ["Simon", "Alex"];) and you will get same results.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.