0

Hi friends I have two variables price1 & price 2, I am getting price value dynamically using onchange event now i want to add these two variables.

//get support layer firmness price
$('.support-layer-firmness').on('change', function(e) {
      //first price
  var price1 = 300;
  });



 $('.support-layer-thickness').on('change', function(e) {
  //second price
  var price2 = 200;

 });


 Now I want to add both variables price1 & price2
eg price = price1+price2;
 o/p  price= 500;

how can i achieve this..

4
  • Do you want to calculate the total price on change? or manually Commented Sep 29, 2016 at 5:26
  • Just use price2 = 200; instead of var price2 = 200; and same for 1. Commented Sep 29, 2016 at 5:26
  • Onchange I am getting price for both varables now i want to add it after that i can append total price somwhere else. Commented Sep 29, 2016 at 5:28
  • define the variables price1 and price2 outside the functions to make them global. Then on onChange event call a function to update the price, e.g updatePrice = function(){return price1 + price2;} Commented Sep 29, 2016 at 5:28

3 Answers 3

1

you need to define global variable for those 2 function like

    var price=0,price1=0,price2=0;
//get support layer firmness price
$('.support-layer-firmness').on('change', function(e) {
      //first price
       price1 = 300;
       price=price1+price2;
       alert(price);
  });



 $('.support-layer-thickness').on('change', function(e) {
  //second price
  price2 = 200;
  price=price1+price2;
  alert(price);
 });
Sign up to request clarification or add additional context in comments.

Comments

1

Make variables as global and set values inside respective change events and then you can add the values anywhere.

$(document).ready(function(){

var price1=0;
var price2=0;

$('.support-layer-firmness').on('change', function(e) {
      //first price
   price1 = 300;
});



 $('.support-layer-thickness').on('change', function(e) {
  //second price
  price2 = 200;
  alert(price1 + price2); //add price
 });

//or you can calculate them on button click 
 $('#btnAdd').click(function(){
   alert(price1 + price2);
  });

});

Comments

0

For access varible from outside. You have to declare variables (price1 & price2) outside the event handle.

var price1,price2; //<= declare here
//get support layer firmness price
$('.support-layer-firmness').on('change', function(e) {
      //first price
  price1 = 300;
  });



 $('.support-layer-thickness').on('change', function(e) {
  //second price
  price2 = 200;

 });

http://www.w3schools.com/js/js_scope.asp

Comments

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.