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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
itmemilan
  • 331
  • 4
  • 17
  • I would recommend you to enter the colors from Javascript, then removing colors, or adding colors, would be easier to achieve. – assembler Nov 11 '21 at 13:48
  • hmm i doing homework and my professor gave it in the html so i can't change it – itmemilan Nov 11 '21 at 13:48
  • 1
    Does this answer your question? [Remove values from select list based on condition](https://stackoverflow.com/questions/12932959/remove-values-from-select-list-based-on-condition) – Liam Nov 11 '21 at 13:49
  • i looked it up earlier and nop i tried – itmemilan Nov 11 '21 at 13:49

2 Answers2

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
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>
Rana
  • 2,500
  • 2
  • 7
  • 28
  • Here values are removed `oninput` event, you must figure out using button click and it is your homework now. – Rana Nov 11 '21 at 14:07