how to do different things with each droplist chioce? HTML

52 views Asked by At

I am creating tax calculator and when the user chooses an option from the drop list choices i want to create a way that each choice will do a different formula in my function. so if the user picks choice 1 it will do formula 1, if they choose option 2 it will do formula 2 so on and so forth. I tried doing so but it forces the last choice every time.

2

There are 2 answers

2
Aswad Sohail On

You can try something like that:

<select id="test">
     <option value=1>Sum</option>
     <option value=2>Difference</option>
</select>

<script>
document.getElementById("test").onchange = function(){
     var test = document.getElementById("test");
     switch(test.options[test.selectedItem].value){
          case 1:
               add();
          break;

          case 2:
               sub();
          break;
     }
}
</script>
8
Deepak Goswami On

You can use something like this:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<select id="myDropdownId">
    <option value="">--choices--</option>
    <option value="1" >formula 1</option>
    <option value="2" >formula 2</option>
    <option value="3" >formula 3</option>
    <option value="4" >formula 4</option>
</select>
<script type="text/javascript">
    $(document).on("change", "#myDropdownId", function() {
        var actionId=$(this).val();

        if (actionId==1) {
            alert('formula 1');
            //formula 1 goes here..
        } else if (actionId==2) { 
            //formula 2 goes here..
        } else if (actionId==3) {
            //formula 3 goes here..
        } else if (actionId==4) {
            //formula 4 goes here..
        } else {
            alert('inavlid formula');
        }
    });
</script>

Please find the demo link below:

DEMO

I hope this helps you. :)