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?
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.
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.
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!
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With