Search code examples
javascriptarraysdependencies

Do dependent dropdown in html using javascript with value and text


I have already a dependent dropdown list in my html form by using only javascript, but when my php script returns values these are just numbered by the position of the text in an array. I would like to have both Value and Text the same value

Here is what I have so far:

SCRIPT IN HEAD TAG:

var my_variable=[
    ["dropA_opt1","dropA_opt2",dropA_opt3"],
    ["dropB_opt1","dropB_opt2",dropB_opt3"],
    ["dropC_opt1","dropC_opt2",dropC_opt3"]
];
function variable(idx) {
    var f=document.my_form;
    f.drop_nr_2.length=null;
    for(var i=0; i<my_variable[idx].length; i++) {
        f.drop_nr_2.options[i]=new Option(my_variable[idx][i], i);
    }
}

SELECT for main DROPDOWN

<select name="drop_nr_1" onchange="my_variable(this.selectedIndex)">
    <option value="" selected disabled></option>
    <option value="value1">value1</option>
    <option value="value2">value2</option>
</select>

SELECT for dependent DROPDOWN

<select name="drop_nr_2">
</select>

The code i have basically creates the options from the array index, but there is no value="" attribute. From that reason I am getting the array index back - but I need a value="same as the text".

In addition it would be nice to have always the first option in the 2nd dropdown selected and disabled with empty value (like in dropdown 1).

Much appreciate your help


Solution

  • When constructing <option> by using javascript object syntax.

    var myOpt = new Option(lbl,val);
    

    The first parameter is the label that user sees it having the second parameter is the value that will be used for this <option> internally.So just modify the constructor line a bit

    f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
    

    For second requirement add a condition for i===0 when it's true pass additional third parameter (wiz. selected) and make disabled property true

    for(var i=0; i<my_variable[idx].length; i++) {
        if(i===0){
            f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i],"selected");
            f.drop_nr_2.options[i].disabled= true;
        } else{
            f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
        }
    }