0

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> 
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Suppe
  • 189
  • 2
  • 5
  • 12

2 Answers2

3

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> 
Dij
  • 9,761
  • 4
  • 18
  • 35
1
<select id="nextGeneration" onchange="abc(this)">
<option value="1">1</option>
<option value="2">2</option> 

</select>

<script>
    function F2() {
        console.log("change 2");
    }

    function F1() {
        console.log("change 1");
    }

    function abc(element) {
        var value1 = element.options[element.selectedIndex].value;

        console.log(value1);

        switch (value1) {
            case "1":
                F1();
                break;
            case "2":
                F2();
                break;

        }
    }
</script>

You need to set your cases in quotes, Ex: case "2".

RC3
  • 59
  • 1
  • 6