Remove Select Option with Specific Value Using Prototype JS

With this html:

<select id='someid'>
    <option value='0'>Value 0</option>
    <option value='1'>Value 1</option>
</select>

How could I remove <option value='0'>Value 0</option> from the select field using Prototype JS?


You don't need Prototype JS to do this.

Removing an option by index:

var select = document.getElementById('someid')
select.removeChild(select.options[0])
<select id='someid'>
    <option value='0'>Value 0</option>
    <option value='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.

function removeOption() {
  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;
}
<select id='someid'>
    <option value='0'>Value 0</option>
    <option value='1'>Value 1</option>
</select>
<br>
Remove option with value: 
  <input id="i0">
  <button onclick="removeOption()">Remove option</button>
  <br>
  <span id="errorMessage"></span>
链接地址: http://www.djcxy.com/p/83082.html

上一篇: 预期状态:<200>但在春季测试中:<404>

下一篇: 使用原型JS删除具有特定值的选项