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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With