As you can see in this example the first box will cause multiplication, but the rest will concatenate ( simply append to ) the last digit present, which increases length but doesn't do any mathematical operation.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sfpm<input id="sfpm">
snom<input id="snom">
bonus<input id="bonus">
<hr/>total<input id="staamount">
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a =$('#sfpm').val();
var b = $('#snom').val();
var c = $("#bonus").val();
var taamount = a*b+c ;
$('#staamount').val(taamount);
});
});
</script>
This is because you're adding two strings together instead of numbers. Strings added together look like this:
let str = "Hello ", str2= "world!";
console.log(str + str2);
So it makes sense that they append. Numbers look like this:
Which does what you expect, but the important thing to realize is that the + operator has multiple functions. it can either append or perform math. The difference as to what type of operation is performed is based solely on the type
of the data you're using.
- a string will append
- a number will add
So in your code when you get the value using .val()
- what's happening is that you're getting string values, not number values. To fix this we can do a few different things.
parseInt
or Number
methods will convert the values from .val()
into integers:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sfpm<input id="sfpm">
snom<input id="snom">
bonus<input id="bonus">
<hr/>total<input id="staamount">
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a = parseInt($('#sfpm').val());
var b = Number($('#snom').val());
var c = parseInt($("#bonus").val());
var taamount = a*b+c ;
$('#staamount').val(taamount || 0);
});
});
</script>
One other way to coerce a string to a number is to simply place the +
operator before the value. This will cause the interpreter to automatically try to change the value into a number.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sfpm<input id="sfpm"> snom
<input id="snom"> bonus
<input id="bonus">
<hr/>total<input id="staamount">
<script type="text/javascript">
$(document).ready(function() {
$('#sfpm,#snom,#bonus').keyup(function() {
var a = +$('#sfpm').val();
var b = +$('#snom').val();
var c = +$("#bonus").val();
var taamount = a * b + c;
$('#staamount').val(taamount || 0);
});
});
</script>