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>
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>
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>