0

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

2
  • -1 because searching SO witn 'Javascript, variables and if/else statements' gives me 1'840 results!! Commented May 13, 2014 at 17:12
  • Apologies. It's my first time here. Commented May 13, 2014 at 17:26

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Slightly updated demo: jsfiddle.net/mNmQs/182 to show how to render the int total the same way as the original question
Thankyou to these comments! You really helped me out! I merged the two to get this which does exactly what I want it to! jsfiddle.net/mNmQs/185
2

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

2 Comments

Wouldn't it make a lot more sense to declare them as ints instead of parsing them?
@ElatedOwl It makes more sense unless the OP wants to show the prices like X.XX instead of just X...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.