Josh
Josh

Reputation: 103

.innerHTML += id, no duplicates

Here what I have so I have a long list of check-boxes and I want to display them in text if they are check I was thinking of using the code below, but the problem I'm having is if they check and uncheck a check-box it shows up multiple times any suggestion on how to fix this?

.innerHTML += id;

If you need some more details here's a code dump of the relevant code:

Javascript

function findTotal() {
    var items = new Array();
    var itemCount = document.getElementsByClassName("items");
    var total = 0;
    var id = '';
    for (var i = 0; i < itemCount.length; i++) {
        id = "c" + (i + 1);
        if (document.getElementById(id).checked) {
            total = total + parseInt(document.getElementById(id).value);
            document.getElementById(id).parentNode.classList.add("active");
            document.getElementById(id).parentNode.classList.remove("hover");
            document.getElementById('display').innerHTML += id;
        } else {
            document.getElementById(id).parentNode.classList.remove("active");
            document.getElementById(id).parentNode.classList.add("hover");
        }
    }
    console.log(total);
    document.getElementById('displayTotal').value = total;
}

HTML

<label class="hover topping" for="c4">
  <input class="items" onclick="findTotal()" type="checkbox" name="topping" value="1.00" id="c4">BABYBEL</label>

Note: many more label classes

Upvotes: 0

Views: 826

Answers (2)

dazlious
dazlious

Reputation: 556

Previous answer should do it. Here your code (see comment "clear container" Additionally I have simplified your code a bit. Readability greatly increased. Maybe you should switch to jQuery in general, much simpler for your example.

var displayElement = document.getElementById('display'),
    displayTotalElement = document.getElementById('displayTotal');

function findTotal() {
    var items = [],
    itemCount = document.getElementsByClassName("items"),
    total = 0,
    id = '';

    // clear container
    displayElement.innerHTML = "";

    for (var i = 0; i < itemCount.length; i++) {
        id = "c" + (i + 1);
        var element = document.getElementById(id),
            elementsParent = element.parentNode;
        if (element.checked) {
            total = total + parseInt(element.value, 10);
            elementsParent.classList.add("active");
            elementsParent.classList.remove("hover");
            displayElement.innerHTML += id;
        } else {
            elementsParent.classList.remove("active");
            elementsParent.classList.add("hover");
        }
    }
    console.log(total);
    displayTotalElement.value = total;
}

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385224

Reset the text before the loop:

document.getElementById('display').innerHTML = '';

At the moment you're just always adding to whatever's already there…

Upvotes: 0

Related Questions