Nick Audenaerde
Nick Audenaerde

Reputation: 1025

How to add value of generated checkboxes to total

The problem description: I have 10 generated checkboxes, that if checked needs to add a price to the total price, but i have the following problem:

I have 4 buttons, that generate checkboxes like this

$('#stdntBtn').on('click', function () {
    cartNumber += 1;
    if (cartNumber > 10) {
        alert(errorMsg);
    } else {
        $('#ticketTable').append('<tr><td>Kaartje ' + cartNumber + ': Studentenkorting $8,00</td><td> <input type="checkbox" id="a' + cartNumber + '" name="popcornArrangement"><label for="b' + cartNumber + '">Popcorn arrangement (+2,50)(medium popcorn en frisdrank naar keuze)</label></td></tr>');
        totalPrice += 8;
        document.getElementById("totalPriceHtml").innerHTML = "Totaal bedrag: &euro;" + totalPrice;
    }
});

so basicly i have id's a1 till a10, since you can't have more then 10 checkboxes. Now I looked up some stuff on google, but all i can find is how to see if a box is checked on base of ID, like this example:

How to check whether a checkbox is checked in jQuery?

but i have 10 different id's, so then i thought i was smart to make a switch statement like this:

switch(cartNumber) { case 1:

        break;

    case 2:

        break;

    case 3:

        break;

    case 4:

        break;

    case 5:

        break;

    case 6:

        break;

    case 7:

        break;

    case 8:

        break;

    case 9:

        break;

    case 10:

        break;

    default: "test"
}

but then i realized that i have no idea how to create a switch statement on it, and perhaps there are other ways of doing this and I'm just thinking wrong. Any idea's?

Upvotes: 0

Views: 27

Answers (1)

devqon
devqon

Reputation: 13997

Something like:

var checkedIds = [];

for(var i = 1; i <= 10; i++) {
    var elem = $("input#a" + i);
    if(elem.is(":checked")) {
        checkedIds.push(i);
    }
}

Upvotes: 1

Related Questions