1

So I am trying to create something where when a user clicks a div element, it adds a number to a total, sort of like a checkout system.

I have written the following javascript

JS

        var optionOne = 5;
        var optionTwo = 10;

        var basePrice = 0;
        function doMath() {
            $("#option1checkout").click(function() {
                // Add optionOne to basePrice
            });
            $("#option1cancel").click(function() {
                // Don't do anything to basePrice
            });
            $("#option2checkout").click(function() {
                // Add optionTwo to basePrice
            });
            $("#option2cancel").click(function() {
                // Don't do anything to basePrice
            });
        };

I want it to add option 1 and 2 to basePrice whenever they click the option1checkout or option2checkout div element and do nothing when they click the cancel div elements.
I just feel like if I just do "basePrice + optionOne;" in the click functions it would be manual and not actually adding the integer values.

Any other way to do this?

1
  • it would be manual and not actually adding the integer values. I don't understand this. What's your problem? What's wrong with basePrice+=optionOne or basePrice+=optionTwo for each click? Commented Oct 1, 2015 at 3:20

1 Answer 1

1

What wrong with this approach:

  var mousePrice = 5;
  var coverPrice = 10;
  var mouseSelected=0;
  var coverSelected=0;
  var basePrice = 500;
    function doMath() {
        $("#mouse").click(function() {
            basePrice+=mousePrice;
        });
        $("#omouseCancel").click(function() {
           if(mouseSelected>0){
               basePrice-=(mousePrice*mouseSelected);
            }
        });
        $("#cover").click(function() {
            basePrice+=coverPrice;
        });
        $("#coverCancel").click(function() {
           if(coverSelected>0){
               basePrice-=(coverPrice*coverSelected);
            }
        });
    };
Sign up to request clarification or add additional context in comments.

2 Comments

Because what if they want to add another item. Say you choose optionOne but also want optionTwo, wouldn't the output of basePrice change from 5 to 10 as you select one?
can you elaborate your requirement more. Is it like you select one main product (say laptop) and then you have list of other tools like mouse , cover ? and you want to calculate the sum of base price and other selected options to calculate the checkout amount

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.