Search code examples
javascriptevent-listenerattachevent

Javascript piece of code not working


My javascript code isn't working, it's supposed to calculate the total price of lunch menu items and give the total result but nothing is coming up. The html is working fine, so I'm just writing the javascript section here, it's short. I literally followed directions to get this code, so I don't get what's wrong. Thank you :)

function calcTotal()
{
    var itemTotal=0;
    var items=document.getElementsByTagName("input"); 
    //collects them into a NodeList object, which has indices

    for(var i=0;i<5;i++)
    {
        if(items[i].checked)
        itemTotal+=(items[i].value*1); //the *1 turns it into a number
    }
    document.getElementById("total").innerHTML="Your order total is $"+itemTotal + ".00";
    var submitButton = document.getElementById("sButton");
    if(submitButton.addEventListener)
    {
        submitButton.addEventListener("click",calcTotal,false);
    }

    else if(submitButton.attachEvent)
    {
        submitButton.attachEvent("onclick", calcTotal);
    }
}

Solution

  • Well, we need to see the HTML, but on first glance, I'd say it's because you are trying to set up your event bindings inside the event callback which won't get called unless you've set up the event bindings. You must set those up fist:

    // First set up the event handling
    var submitButton = document.getElementById("sButton");
    
    // In this case, you can just check window to see if it has the property
    if(window.addEventListener) {
      submitButton.addEventListener("click",calcTotal,false);
    } else if(window.attachEvent)  {
      submitButton.attachEvent("onclick", calcTotal);
    }
    
    // And, have the callback separate
    function calcTotal() {
        var itemTotal=0;
        var items=document.getElementsByTagName("input"); 
        //collects them into a NodeList object, which has indices
    
        for(var i=0;i<5;i++) {
            if(items[i].checked)
            itemTotal+=(items[i].value*1); //the *1 turns it into a number
        }
    
        document.getElementById("total").innerHTML="Your order total is $"+itemTotal + ".00";
    }