mercredi 13 mai 2015

Asign a number value to a global variable using Case Switch

I am a beginner in JavaScript and I would like to simulate an exercise using HTML and JavaScript. Basically, I have two inputs that take 1: the name of a product and 2) the quantity of this item. When user click on a button, the function that calculates the total amount for that item is executed. On this function, I use switch statement in order to calculate the right $amount according to the product. Then the function should print the itemTotal which is the result of the itemQ (Quantity of the item) * a fix value for that item (3.5 for eggs). But itemTotal appear with 0 zero. It seems that the switch statement does not recognize it. If I make it a local value inside switch, then I cannot used outside of switch statement. What can I do? Any ideas?

<!DOCTYPE html>

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <title>My register - jsFiddle demo</title>

  <script type="text/javascript">
    function calTotItemA(){

        var item = document.getElementById("itemName").value;
        var itemQ = document.getElementById("itemQuantity").value;
        var itemTotal = 0;


        switch(item){
            case "eggs": this.itemTotal = 3.5 * itemQ; break;
            case "milk": this.itemTotal = 4.5 * itemQ; break;
        }


        document.getElementById("itemTotalDisplay").innerHTML = itemTotal;

}


</script>

 <link rel="stylesheet" type="text/css" href="file://file2/css/result-light.css">

 <style type="text/css">
    header{

    background-color: #83BD26;
    }
    h1{
        text-align:center;
    }


    #pad{
        background-color: #B5BFA4;    
    }

    #container{
         border: 3px solid black;

    }

    #itemBox{
        height:3px;
        widht:

    }
</style>

</head>
<body>

        <div id="container">
            <header><h1>My Cash Register</h1></header>
            <div id="pad">
                <form>Enter item  
                      <input type="text" id="itemName" value=" ">
                </form>
                <form>Enter quantity of the item  
                       <input type="number" id="itemQuantity" value="0">
                </form>
                       <button onclick="calTotItemA()">Calculate Total Amount per Item </button>
                      <p>The total amount for this item: </p>
                      <p id="itemTotalDisplay"></p>
                 </div>
            </div>
</body>
</html>




Aucun commentaire:

Enregistrer un commentaire