Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change options of a select using JavaScript

I have an HTML page in which I have 2 selects.

<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 options for going back to having all the ones listed above).

I can't think of another solution, any help would be greatly appreciated.

like image 285
avorum Avatar asked Jul 31 '13 17:07

avorum


2 Answers

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;
        };
    }
}
like image 189
Sergio Avatar answered Oct 11 '22 15:10

Sergio


To manipulate options when Plugin ID was selected:

function checkValidOption(){
    var x=document.getElementById("field");
    var y=document.getElementById("operator");
    if (x.options[1].selected === true){
        document.getElementById("operator").options[1].selected = true;
        for(var i=0; i<y.length; i++){
            if (i !== 1){
                //disabling the other options 
                document.getElementById("operator").options[i].disabled = true;     
            }
        }
    }       
    else{
        for(var i=0; i<y.length; i++){
            //enabling the other options 
            document.getElementById("operator").options[i].disabled = false;     
        }
    }
}

Here's a link to fiddle

like image 42
Nir Alfasi Avatar answered Oct 11 '22 15:10

Nir Alfasi