Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove values from select list based on condition

I have the following in the page

<select name="val" size="1" > <option value="A">Apple</option> <option value="C">Cars</option> <option value="H">Honda</option> <option value="F">Fiat</option> <option value="I">Indigo</option>                     </select>  

I would like to remove certain values from my select if certain conditions are true.

E.g

if(frm.product.value=="F"){   // remove Apple and Cars from the select list } 

How can I do this using javascript

like image 481
Jacob Avatar asked Oct 17 '12 11:10

Jacob


People also ask

How do I disable a specific item in a dropdown element?

The drop-down is used to create a list of items that need to select an element. We use <select> and <option> elements to create a drop-down list and use disabled attribute in <select> element to disable the drop-down list element.

How do I remove a selected value from a Dropdownlist?

First, bind click event on the button using click . Use the :selected pseudo-selector to select the selected option from the dropdown and remove() to remove it from DOM.

How do I remove a selected value from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How to remove an item from dropdownlist in JavaScript?

To remove an option from a dropdown list, you can use jQuery's . remove() method. The . remove() method will remove the specified elements out of the DOM.


1 Answers

Give an id for the select object like this:

<select id="mySelect" name="val" size="1" >     <option value="A">Apple</option>     <option value="C">Cars</option>     <option value="H">Honda</option>     <option value="F">Fiat</option>     <option value="I">Indigo</option>                     </select>  

You can do it in pure JavaScript:

var selectobject = document.getElementById("mySelect"); for (var i=0; i<selectobject.length; i++) {     if (selectobject.options[i].value == 'A')         selectobject.remove(i); } 

But - as the other answers suggest - it's a lot easier to use jQuery or some other JS library.

like image 124
Andrew Avatar answered Sep 21 '22 21:09

Andrew