SangheiliDragon SangheiliDragon - 2 months ago 27
Javascript Question

Select option calculation with switch case

What I'm trying to do is have a drop down menu, select an option in this case I want 2 bottles of jwWhisky. I want it to then go to the js and have the switch case enter the price for the bottle and multiply it by the bottles I want.

The HTML:



function calculate() {
"use strict"
var myBox1 = document.getElementById('drinks1Num').value;
var myBox2 = document.getElementById('drinks1Type').value;
var result = document.getElementById('result');
var myResult = myBox1 * myBox2;
var inputCost = 0;
switch (myBox2) {
case 'jwWhisky':
inputCost = 49;
break
//default:
// alert ("You haven't coded this yet");
}

result.value = myResult;
}

<legend>
Sprits Option
</legend>
<select id="drinks1Num" onchange="calculate()">
<option value="0">--- Select ---</option>
<option value="1">1</option>
<option value="2">2</option>
</select>

<select id="drinks1Type" onchange="calculate()">
<option value="0">--- Select ---</option>
<option disabled="disabled"></option>
<optgroup label="whisky">
<option value="jwWhisky">Johnnie Walker 700ml</option>49$
</optgroup>
</select>
<input id="result" />




Answer

You just need to move the calculation of myBox1 * inputCost to after your switch:

function calculate() {
        "use strict"
        var myBox1 = document.getElementById('drinks1Num').value;   
        var myBox2 = document.getElementById('drinks1Type').value;
        var result = document.getElementById('result'); 
        var inputCost=0;
  
        switch (myBox2) {
            case 'jwWhisky':
                inputCost=49;
                break
            //default:
            //  alert ("You haven't coded this yet");
        }

        result.value = myBox1 * inputCost;
}
<select id="drinks1Num" onchange="calculate()">
  <option value="0">--- Select ---</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

<select id="drinks1Type" onchange="calculate()">
  <option value="0">--- Select ---</option>
  <option disabled="disabled"></option>
  <optgroup label="whisky">
    <option value="jwWhisky">Johnnie Walker 700ml</option>49$
  </optgroup>
</select>
<input id="result" "/>

(Also, as you can see, you don't really need the myResult variable at all.)

Note that it would probably be nicer to just store the prices as data-price attributes on each option element, as that would keep the product information together in one place in the HTML and you wouldn't need a JS switch statement.

Comments