How to change options of a select using JavaScript

html, javascript, select

Solution

Try this:

Demo here

var field = document.getElementById('field');
var operator = document.getElementById('operator');
field.onchange = function () { fieldcheck(); }
operator.onchange = function () { fieldcheck(); }
fieldcheck();

function fieldcheck() {
    if (field.value == 'Plugin ID') {
        for (i = 0; i < operator.options.length; ++i) {
            if (operator.options[i].value != 'EQUALS') {
                operator.options[i].disabled = true;
            }
        };
        operator.value = 'EQUALS';
    } else {
        for (i = 0; i < operator.options.length; ++i) {
            operator.options[i].disabled = false;
        };
    }
}

Problem

I have an HTML page in which I have 2 `select`s. ``` <select id="field" name="field" onchange="checkValidOption();"> <option /> <option value="Plugin ID">Plugin ID</option> <option value="Name">Name</option> </select> <select id="operator" name="operator" onchange="checkValidOption();"> <option /> <option value="EQUALS">EQUALS</option> <option value="CONTAINS">CONTAINS</option> <option value="NOT CONTAINS">NOT CONTAINS</option> <option value="REGEX">REGEX</option> </select> ``` What I'd like to happen is that `checkValidOption()` could make it so that if "Plugin ID" is selected in field that the only option is EQUALS (and it's selected) and otherwise all the other options are available. Any idea on how to approach this? I tried changing the `innerHTML` of the operator select in JS: ``` document.getElementById("operator").innerHTML = "<option value='EQUALS'>EQUALS</option>"; ``` However this results in an empty `select` (this would also include manually setting the many `option`s for going back to having all the ones listed above). I can't think of another solution, any help would be greatly appreciated.

Original source