Dean TristaNato
Dean TristaNato

Reputation: 133

Select Option HTML with Switch Javascript

I want to if you select an option on the brandSelect, the option on the socketSelect will appear, and I have a code like this

<select id="brandSelect" onchange="brandSelect()">
        <option value="10">Pilih Brand</option>
        <option value="20">AMD</option>
        <option value="30">Intel</option>
</select>

<select id="socketSelect">
        <option>Pilih Socket</option>
</select>

and

function brandSelect(){
    var x = document.getElementById("brandSelect");
    var selectedValue = x.options[x.selectedIndex].value;

    switch(selectedValue){
        case 10:
            break;
        case 20:
            var x = document.getElementById("socketSelect");
            var am4 = document.createElement("option");
            var am3 = document.createElement("option");
            var am2 = document.createElement("option");
            am4.text = "AM4";
            am3.text = "AM3";
            am2.text = "AM2";
            x.add(am4);
            x.add(am3);
            x.add(am2);
            break;
        case 30:
            break;
    }
}

And why my code still won't work?

Upvotes: 2

Views: 367

Answers (1)

catcon
catcon

Reputation: 1363

Your code does not work because in javascript, switch compare value using === which checks for both data type and value, and the value from x.options[x.selectedIndex].value; is string type while you compare with int type. You have to convert your value to integer type before comparing using switch.

<select id="brandSelect" onchange="brandSelect()">
        <option value="10">Pilih Brand</option>
        <option value="20">AMD</option>
        <option value="30">Intel</option>
</select>

<select id="socketSelect">
        <option>Pilih Socket</option>
</select>


<script type="text/javascript">
function brandSelect(){
    var x = document.getElementById("brandSelect");
    var selectedValue = parseInt(x.options[x.selectedIndex].value); //parse your value to integer

    switch(selectedValue) {
        case 10:
            break;
        case 20:
            var y = document.getElementById("socketSelect");
            var am4 = document.createElement("option");
            var am3 = document.createElement("option");
            var am2 = document.createElement("option");
            am4.text = "AM4";
            am3.text = "AM3";
            am2.text = "AM2";
            y.add(am4);
            y.add(am3);
            y.add(am2);
            break;
        case 30:
            break;
    }
}
</script>

Demo: https://jsfiddle.net/t7umjq2y/

Upvotes: 2

Related Questions