mercredi 31 août 2016

Why does my program keep creating new elements?

This is part of the interactivity of a form.

A user can select from a range of activities. 6 of the activities are priced as 100, one of them is priced at 200.

As the user checks the boxes, a label appears, telling the user what the total price is.

Right now, the price is being calculated fine.

But every single time a box is checked, a NEW label is added. As opposed to updating the old one. Why is this happening?

This is my code:

// Register for Activities section of the form.
document.querySelector(".activities").addEventListener("change", function(){
    var main = document.getElementById("all");
    var framework = document.getElementById("framework");
    var libs = document.getElementById("libs");
    var express = document.getElementById("express");
    var node = document.getElementById("node");
    var build = document.getElementById("build");
    var npm = document.getElementById("npm");

    // Calculate running total of price of events selected
    var mainPrice = 200;
    var otherPrice = 100;
    var totalPrice = 0;


    if(!totalLabel){
        var totalLabel = document.createElement('label');
        activities.appendChild(totalLabel);
    }

    if(main.checked == true){
        totalPrice += mainPrice;
    }
    if(framework.checked == true || express.checked == true) {
        totalPrice += otherPrice;
    } 
    if(libs.checked == true || node.checked == true) {
        totalPrice += otherPrice;
    } 
    if(build.checked == true) {
        totalPrice += otherPrice;
    } 
    if(npm.checked == true) {
        totalPrice += otherprice;
    }

    var totalNumber = totalPrice.toString();
    var totalText = "Total is $" + totalNumber;

    totalLabel.innerHTML = totalText;
});

I assumed this would be a problem before, I thought this would fix it by only creating a new element if totalLabel didn't already exist :

if(!totalLabel){
        var totalLabel = document.createElement('label');
        activities.appendChild(totalLabel);
    }

Any suggestions please guys?




Aucun commentaire:

Enregistrer un commentaire