JQuery Automatic Add Two Numbers From Text Fields
I am trying to add two numbers whenever a keyup happens in the textboxes of those two numbers. I want it to use jquery so my addition code is these: HTML:
Solution 1:
use parseInt()
to convert string
to Number
function calc() {
var $num1 = ($(".num1").val() != "" && !isNaN($(".num1").val())) ? parseInt($(".num1").val()) : 0;
var $num2 = ($(".num2").val() != "" && !isNaN($(".num2").val())) ? parseInt($(".num2").val()) : 0;
$(".sum").val($num1 + $num2);
}
Your overall code should look like this:
$(document).ready(function() {
$(".sum").val("0");
$(".key").val("");
function calc() {
var $num1 = ($.trim($(".num1").val()) != "" && !isNaN($(".num1").val())) ? parseInt($(".num1").val()) : 0;
console.log($num1);
var $num2 = ($.trim($(".num2").val()) != "" && !isNaN($(".num2").val())) ? parseInt($(".num2").val()) : 0;
console.log($num2);
$(".sum").val($num1 + $num2);
}
$(".key").keyup(function() {
calc();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1>jQuery live Try</h1>
<form>
<input type="text" placeholder="Number 1" class="num1 key">
<input type="text" placeholder="Number 2" class="num2 key">
<br><br>
Sum: <input type="text" class="sum" readonly="readonly"><br><br><br>
</form>
</div>
Solution 2:
the .val()
method return a string
, string 1 + string 2 = 12
.
So use the parseFloat
method.
change
var $num1=$(".num1").val();
var $num2=$(".num2").val();
to
var $num1=parseFloat($(".num1").val());
var $num2=parseFloat($(".num2").val());
Solution 3:
You should parse the string representation to Integer
var $num1=parseInt($(".num1").val());
var $num2=parseInt($(".num2").val());
Solution 4:
The value returned from jQuery is a string
so you have to cast your value into integers
:
var $num1=parseInt($(".num1").val(), 10) || 0;
var $num2=parseInt($(".num2").val(), 10) || 0;
$(".sum").val($num1+$num2);
or use parseFloat()
if you want to support floating numbers
.
Another possibilty would be to use the Number()
-function, as this will cast an empty string automatically:
var $num1=Number($(".num1").val());
var $num2=Number($(".num2").val());
Reference
Post a Comment for "JQuery Automatic Add Two Numbers From Text Fields"