使用Prototype JS删除具有特定值的选择选项

时间:2016-12-13 01:59:31

标签: javascript select prototypejs

使用这个html:

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

如何使用Prototype JS从select字段中删除<option value='0'>Value 0</option>

2 个答案:

答案 0 :(得分:1)

你不需要Prototype JS就可以做到这一点。

按索引删除选项:

&#13;
&#13;
var select = document.getElementById('someid')
select.removeChild(select.options[0])
&#13;
<select id='someid'>
    <option value='0'>Value 0</option>
    <option value='1'>Value 1</option>
</select>
&#13;
&#13;
&#13;

删除具有特定value

的选项

&#13;
&#13;
var select = document.getElementById('someid')
select.removeChild(getOptionByValue(select, '0'))

function getOptionByValue (select, value) {
    var options = select.options;
    for (var i = 0; i < options.length; i++) {
        if (options[i].value === value) {
            return options[i]  
        }
    }
    return null
}
&#13;
<select id='someid'>
    <option value='0'>Value 0</option>
    <option value='1'>Value 1</option>
</select>
&#13;
&#13;
&#13;

或受this answer的启发:

编辑: RobG submitted this technique before me;此后所有信用都归功于他。我看到他的评论批评了我的回答,并开始相应地编辑我的帖子,但没有向下滚动足以看到他的答案,已经解决了这个问题。)

&#13;
&#13;
var select = document.getElementById('someid')
select.removeChild(select.querySelector('option[value="0"]'))
&#13;
<select id='someid'>
    <option value='0'>Value 0</option>
    <option value='1'>Value 1</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用选择器获取具有特定值的选项,然后将其删除。以下使用 querySelector ,但您也可以遍历所有选项并找到具有所需值的选项,并以相同的方式删除它们。

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>

相关问题