0

How can i remove options on click of a button that are nested inside an select element?

Is my mistake in for loop ? I can't figure it out

var select = document.getElementById('colorSelect'); var options = document.getElementsByTagName('option'); console.log(options); function removecolor() { for (var i = 0; i < options.length; i++) { console.log(select.value); //Here i need to delete option value that is selected } }
<form> <select id="colorSelect"> <option>Red</option> <option>Green</option> <option>White</option> <option>Black</option> </select> <input type="button" onclick="removecolor()" value="Select and Remove"><br> </form>

4
  • I would recommend you to enter the colors from Javascript, then removing colors, or adding colors, would be easier to achieve. Commented Nov 11, 2021 at 13:48
  • hmm i doing homework and my professor gave it in the html so i can't change it Commented Nov 11, 2021 at 13:48
  • 1
    Does this answer your question? Remove values from select list based on condition Commented Nov 11, 2021 at 13:49
  • i looked it up earlier and nop i tried Commented Nov 11, 2021 at 13:49

2 Answers 2

0

Just use .remove

const select = document.getElementById('colorSelect'); document.getElementById("remove").addEventListener("click",function() { const opt = select.options[select.selectedIndex]; if (opt) opt.remove() })
<form> <select id="colorSelect"> <option>Red</option> <option>Green</option> <option>White</option> <option>Black</option> </select> <input type="button" id="remove" value="Select and Remove"><br> </form>

If you are not allowed to change the HTML and event handler you can do

const select = document.getElementById('colorSelect'); function removecolor() { const opt = select.options[select.selectedIndex]; if (opt) opt.remove() }
<form> <select id="colorSelect"> <option>Red</option> <option>Green</option> <option>White</option> <option>Black</option> </select> <input type="button" onclick="removecolor()" value="Select and Remove"><br> </form>

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

Comments

0

The linked question will solve your problem, with a slight changes.

Here values are removed using oninput event

var selectobject = document.getElementById("colorSelect"); function func() { console.log(selectobject.value) selectobject.options[selectobject.selectedIndex].remove(); }
<select id="colorSelect" oninput="func()"> <option>Red</option> <option>Green</option> <option>White</option> <option>Black</option> </select>

1 Comment

Here values are removed oninput event, you must figure out using button click and it is your homework now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.