I am trying to get values from input field using .each()
and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am
your appending String. $(this).val()
is a string . just parse it to int or float.
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);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>
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);
});
You are adding a NaN data type to an Number data type. So you need to restrict it before you perform your addition operation.
Please check this one
var totalvalue = 0;
$(document).on("focusout",".value",function() {
$(".value").each(function() {
if(isNaN($(this).val()) || $(this).val() != ''){
totalvalue = totalvalue + parseInt($(this).val());
}
});
$("#totalvalue").val(totalvalue);
});
What you're parsing line is saying is
Add the
totalValue
to the string from the input, then parse the result.
Which is why it's concatenating. Instead, you need to add the totalValue
outside of the parseInt()
so that it's saying
Take the take the
totalValue
and add the parsed input value to it.
Like this
totalvalue = totalvalue + parseInt($(this).val());
This can be further shortened to
totalvalue += parseInt($(this).val());
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.