0

I have the following HTML

HTML

<h1 id="total"></h1>
<div id="option1" onclick="doMath()">Option 1</div>
<div id="option2" onclick="doMath()">Option 2</div>

And the following Javascript
JS

    var basePrice = 0;
    var optiononePrice = 5;
    var optiontwoPrice = 10;

    function doMath() {
        $("#option1").click(function() {
            basePrice += 5;
        });
        $("#option2").click(function() {
            basePrice += 10;
        });
    };
    $("#total").html(basePrice);

When a user clicks a div element, the price should add to the total, but this is what happens:

For example, the user clicks option1. The basePrice will print "5", but when they click option1 again, the basePrice goes from "5" to "15", then from "15" to "30" and goes like that every click. Same with option2, it starts at "10", then goes from "10" to "30" and so on.

What is happening, how should I fix this?

2
  • 5
    You keep on adding listeners on each click, so with each click the function gets called another time. All you have to do is put everything on doMath outside, delete doMath and delete onclick=doMath(). Commented Oct 2, 2015 at 1:57
  • Separate doMath into two methods and see what happens. Commented Oct 2, 2015 at 2:00

1 Answer 1

2

You can try this code

HTML

<h1 id="total"></h1>
<div id="option1">Option 1</div>
<div id="option2">Option 2</div>

Javascript

var basePrice = 0;
var optiononePrice = 5;
var optiontwoPrice = 10;    

    $("#option1").click(function() {
        basePrice += 5;
    });
    $("#option2").click(function() {
        basePrice += 10;
    });

$("#total").html(basePrice);
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks, I will select this as best answer in 6 mins (when I can)

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.