techiva.blogspot.com
techiva.blogspot.com

Reputation: 1180

Add two variable using jquery

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

Answers (3)

Mudassir Hasan
Mudassir Hasan

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

Quy Truong
Quy Truong

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;

 });

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

Upvotes: 0

Rakesh Sojitra
Rakesh Sojitra

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

Related Questions