Add two variables using jquery

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)

Leave a Comment