user1240207
user1240207

Reputation: 217

Remove select option with specific value

How can I remove <option value="0">Value 0</option> from the <select> menu based on the value 0?

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

Upvotes: 3

Views: 12469

Answers (2)

gyre
gyre

Reputation: 16777

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>

Removing an option with a specific value:

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
}
<select id='someid'>
    <option value='0'>Value 0</option>
    <option value='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"]'))
<select id='someid'>
    <option value='0'>Value 0</option>
    <option value='1'>Value 1</option>
</select>

Upvotes: 3

RobG
RobG

Reputation: 147453

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>

Upvotes: 2

Related Questions