Javascript - Returning Concatenates Instead Of Sum Of Variables From Input
Solution 1:
What you're parsing line is saying is
Add the
totalValueto the string from the input, then parse the result.
Which is why it's concatenating. Instead, you need to add the totalValueoutside of the parseInt() so that it's saying
Take the take the
totalValueand add the parsed input value to it.
Like this
totalvalue = totalvalue + parseInt($(this).val());This can be further shortened to
totalvalue += parseInt($(this).val());
Solution 2:
You should declare totalvalue inside focusout function ,because it will always show the total of two input text and pass the input value empty state when sum !!!
$(document).on("focusout",".value",function() {
var totalvalue = 0;
$(".value").each(function() {
if($(this).val() == "") return;
totalvalue += parseInt($(this).val());
});
$("#totalvalue").val(totalvalue);
});
Solution 3:
your appending String. $(this).val() is a string . just parse it to int or float.
Solution 4:
If your purpose is this according to your code then it will always sum up with first box value.
var value = parseInt($(this).val());
if(value)
totalvalue = totalvalue + value;
});
Otherwise you should elaborate your question so that proper answer could be provided.
Solution 5:
Try with parseFloat() on input value
parseFloat($(this).val()));
var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
$(".value").each(function() {
totalvalue = (totalvalue + parseFloat($(this).val()));
});
$("#totalvalue").val(totalvalue);
});<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype=textname=value[]id=valueclass="value"><inputtype=textname=totalvalueid=totalvalue>
Post a Comment for "Javascript - Returning Concatenates Instead Of Sum Of Variables From Input"