Вопрос

I'm a complete Javascript newbie and I'm helping my friend with a small project for college.

The idea is that when a checkbox is checked an item is chosen, and then when a "total" button is pressed, the sum of the checked items is printed. I've been using if/else statements so if checked var staticprice = 29.00 and else var staticprice = 0.00, which appears to work fine until I total it. Adding the variable "staticprice" always returns a value of 0.00, even when checked.

It's very messy (as is my first attempt creating something like this): http://jsfiddle.net/mNmQs/180/

What am I missing here?

Cheers

Это было полезно?

Решение

Couple of things to make life easier, give your checkboxes a value, that is what it's there for! I've updated your fiddle to include the appropriate values per checkbox. The next is loops, simply loop your checkboxes, if checked, add the value of the checked input to the total:

var totalBtn = document.getElementById("total"),
checkboxes = document.getElementsByTagName("input");

totalBtn.onclick = function() {
    var total = 0;
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked) {
            total = total + parseInt(checkboxes[i].value);
        }
    }

    alert(total);
}

http://jsfiddle.net/mNmQs/181/

Другие советы

You could change this line:

this.grandTotal= +seaprice + +stillprice + +staticprice; 

To:

grandTotal= parseInt(seaprice,10) + parseInt(stillprice,10) + parseInt(staticprice,10); 

In this case the problem is that you're trying to sum strings instead of numbers

JSFiddle example

HOWEVER it seems in this case there's no point in declaring your prices as strings. Of course unless you wanted to show the prices with in the format 0.00, otherwise just declare them as numbers and that should be better, like: var seaprice = 39.00; or var seaprice = 39.00; instead of var seaprice = "39.00";

Other fiddle

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top