Reputation: 1180
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..
Upvotes: 0
Views: 2186
Reputation: 28741
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);
});
});
Upvotes: 1
Reputation: 413
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;
});
Upvotes: 0
Reputation: 3658
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);
});
Upvotes: 1