Here is what I'm trying to do.
I have a form with different fields set up in the following structure:
<input type="text" id="revenue-1" />
<input type="text" id="revenue-2" />
<input type="text" id="revenue-3" />
<input type="text" id="revenue-4" />
<input type="text" id="revenue-5" />
I get the values by using the following code:
$("input[id^='revenue-']").keyup(function(e) {
var revenue = $("#revenue-" formNumber).val();
});
Here is what I want to do, I want to get the values and increment each time. For example, if revenue-1 is 90 and revenue-2 is 100 the total value of those fields automatically?
Basically, I want to get all the numeric values of all of the fields to add up each time I enter a value on the form and it will display elsewhere.
Thank you, Kevin Davis
CodePudding user response:
Consider the following.
$(function() {
function calcTotal() {
var c = 0;
$("[id^='revenue']").each(function() {
var v = $(this).val();
if (parseInt(v)) {
c = parseInt(v);
}
});
return c;
}
$("[id^='revenue']").keyup(function(event) {
console.log(event.key, calcTotal());
});
});
input[type='text'] {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="revenue-1" />
<input type="text" id="revenue-2" />
<input type="text" id="revenue-3" />
<input type="text" id="revenue-4" />
<input type="text" id="revenue-5" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
This examines each of the fields, and if they have a number entry, will combine them with any other fields.
Remember that Text Fields result in String content. So if the user enters 1
, the .val()
will respond with "1"
, a String. So to perform a math calculation, we need to use parseInt()
to cast it as a Integer.
See More: https://api.jquery.com/each/