Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two variables using jquery

var a = 1; var b = 2; var c = a+b; 

c will show as 12; but I need 3

How do I do it using jQuery?

like image 354
X10nD Avatar asked Sep 28 '10 10:09

X10nD


People also ask

How do you add two variables in HTML?

You can then add numbers in the first two text boxes and store them in a variable such as "result," as follows: var result = Number(box1. value) + Number(box2. value); box3.

How do I set the value of a element in JQuery?

JQuery val() method: This method return/set the value attribute of selected elements. If we use this method to return value, it will return the value of the FIRST selected element. If we use this method to set value, it will set one or more than one value attribute for set of selected elements.


2 Answers

Definitely use jQuery

Because the power of jQuery is obviously unparalleled, here is how to do with with 100% jQuery:

var a = 1; var b = 2; $("<script>c=+("+a+")+ +("+b+")</script>").appendTo($(document)); 

Now c will hold your result and you used nothing but jQuery! As you can see jQuery is really great because it does all sorts of things

This also works well because it doesn't matter if a or b are strings!


Not enough jQuery?

var a = 1; var b = 2; $("<script id='test'>$('<textarea id=\\'abc\\'>'+("+a+")+ +("+b+")+'</textarea>').appendTo($('body'))</script>").appendTo('body'); var c = $("#abc").val(); 

This answer was done with 100% jQuery because jQuery is awesome but only use this carefully because it might not work sometimes.


jQuery Arithmetic Plugin

You can also use the revolutionary jQuery Arithmetic Plugin this has solved world peace in over 4294967295 (>> 0 === -1) countries:

var a = 1; var b = 2; var c = $.add(a,b); 

while this is all great (this is not confirmed), but in jQuery -3.0.1 I have heard you will be able to add numbers this way:

$.number($.one, $.two).add($.number($.three, $.four)) 

this adds 12 (one + two) to 34 (three + four)

like image 112
Downgoat Avatar answered Sep 23 '22 02:09

Downgoat


It looks like you have strings and not numbers, you need parseInt() or parseFloat() (if they may be decimals) here, like this:

var a = "1"; var b = "2"; var c = parseInt(a, 10) + parseInt(b, 10); //or: var c = parseFloat(a) + parseFloat(b); 

You can test the difference here, it's worth noting these are not jQuery but base JavaScript functions, so this isn't dependent on the jQuery library in any way.

like image 30
Nick Craver Avatar answered Sep 21 '22 02:09

Nick Craver