I am trying to get the sum of the values entered into the age input fields upon change. Then I need to validate the sum of ages against the total number of students trained. If the total number of students trained does not match the sum of the students ages I want to throw an error. I am coding in C#.
Here is my html code:
<h4>Training</h4>
<b>Total number of students in training:</b> <input type="number" name="Total Number students trained" min="0"><span style="color: #f00">
<h5>Ages of Students </h5>
<table>
<tr>
<td><label for="age 18" class="float-left"> <18:</label> <input type="number" min="0" max="500" name="age 18" oninput="calcage"> </td>
<td><label for="age 24" class="float-left">18-24:</label> <input type="number" min="0" name="age 24 oninput="calcage"> </td>
<td><label for="age 34" class="float-left">25-34:</label> <input type="number"min="0" name="age 34" oninput="calcage"> </td>
<td><label for="age 44" class="float-left">35-44:</label> <input type="number" min="0" name="age 44" oninput="calcage"> </td>
</tr>
</table>
Here is my javascript:
function calcage() {
var score = 0;
$(".age:input").each(function () {
score += parseInt(this.value);
});
$("input[name=Score]").val(score)
}
$().ready(function () {
$(".age").change(function () {
calcage()
});
});
Your HTML has a few errors:
<input>elements need to haveclass="age"added to them so that they are recognized by the$(".age:input").each()function.nameof your second<input>element is missing the closing double quote (").()) after thecalcagecalls in youroninputevents. However, since you are using the$(".age").change()function to call thecalcage()function, it is not necessary to also have theoninputevent call thecalcage()function. Also, theoninputevent is called every time an input changes without waiting until all changes are complete. This means that if a student entered an age of "30", thecalcagefunction would be called twice: first for the "3", and then again for the "0". Since this is not what you want, those event handlers can be removed from the inputs. Leave$(".age").change()since this will only fire once the student has finished typing. It will work once your<input>elements have theclass="age"added to them.<label>elements for attribute will only work when there is an<input>element with a matchingidvalue.Try the following corrected HTML: