You don't need Prototype JS to do this.
Removing an option by index:
var select = document.getElementById('someid')
select.removeChild(select.options[0])
<selectid='someid'><optionvalue='0'>Value 0</option><optionvalue='1'>Value 1</option></select>
Removing an option with a specific value
:
var select = document.getElementById('someid')
select.removeChild(getOptionByValue(select, '0'))
functiongetOptionByValue (select, value) {
var options = select.options;
for (var i = 0; i < options.length; i++) {
if (options[i].value === value) {
return options[i]
}
}
returnnull
}
<selectid='someid'><optionvalue='0'>Value 0</option><optionvalue='1'>Value 1</option></select>
Or, inspired by this answer:
(Edit:RobG submitted this technique before me; all credit hereafter to him. I saw his comment critiquing my answer and began editing my post accordingly, but didn't scroll down far enough to see his answer as well, which had addressed that issue already.)
var select = document.getElementById('someid')
select.removeChild(select.querySelector('option[value="0"]'))
<selectid='someid'><optionvalue='0'>Value 0</option><optionvalue='1'>Value 1</option></select>
You can use a selector to get an option with a specific value, then remove it. The following uses querySelector, but you could also loop over all the options and find the one(s) with the required value and remove them the same way.
functionremoveOption() {
var optValue = document.getElementById('i0').value;
var errorEl = document.getElementById('errorMessage');
var optElement = document.querySelector('option[value="' + optValue + '"]');
if (optElement) {
errorEl.textContent = '';
optElement.parentNode.removeChild(optElement);
} else {
errorEl.textContent = 'There is no option with value "' + optValue + '"';
}
}
#errorMessage {
background-color: white;
color: red;
}
<selectid='someid'><optionvalue='0'>Value 0</option><optionvalue='1'>Value 1</option></select><br>
Remove option with value:
<inputid="i0"><buttononclick="removeOption()">Remove option</button><br><spanid="errorMessage"></span>
Post a Comment for "Remove Select Option With Specific Value"