Search code examples
javascriptswitch-statementhtml-selectonchange

Call a custom function based on selected select field option


I got a problem with this code below.

I want to choose between 2 options. When i choose "1", then F1() is called. When choose "2", then F2() is called.

Unfortunately something is wrong with my code.

function abc(element){
    var value1 = element.options[element.selectedIndex].value;
    
    switch(value1){
        case 1:
            F1();
            break;
        case 2:
            F2();
            break;
    }
}
<select id = "nextGeneration" onchange="abc(this)" >
   <option value="1">1</option>
   <option value="2">2</option>
</select> 


Solution

  • your code is not working because element.options[element.selectedIndex].value returns string values and you are comparing them against integers. In the code below selecting 2 works because it has case for "2" but selecting 1 doesn't work

    function F1(){
    console.log(1);
    }
    function F2(){
    console.log(2);
    }
    function abc(element){
                    var value1 = element.options[element.selectedIndex].value;
                    switch(value1){
                        case 1:
                            F1();
                            break;
                        case "2":
                            F2();
                            break;
    
                    }
                }
    <select id = "nextGeneration" onchange="abc(this)" >
    <option value="1">1</option>
    <option value="2">2</option> 
    
      </select>