添加输入字段并使用 javascript 根据总计验证总和

Add input fields and validate the sum against total using javascript

我正在尝试获取更改后输入到年龄输入字段中的值的总和。然后我需要根据受训学生总数验证年龄总和。如果受训学生总数与学生年龄总和不匹配,我想抛出一个错误。我正在用 C# 编码。

这是我的 html 代码:

<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"> &#060;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>

这是我的 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()
    });
});

您的 HTML 有一些错误:

  1. 您的 <input> 元素需要添加 class="age" 才能被 $(".age:input").each() 函数识别。
  2. 第二个 <input> 元素的 name 缺少右双引号 (")。
  3. 您在 oninput 事件中 calcage 调用后缺少括号 (())。但是,由于您正在使用 $(".age").change() 函数来调用 calcage() 函数,因此没有必要让 oninput 事件也调用 calcage() 函数。此外,每次输入更改时都会调用 oninput 事件,而不会等到所有更改都完成。这意味着如果学生输入的年龄是“30”,calcage 函数将被调用两次:第一次是“3”,然后是“0”。由于这不是您想要的,因此可以从输入中删除这些事件处理程序。保留 $(".age").change() 因为这只会在学生完成输入后触发。一旦您的 <input> 元素添加了 class="age",它就会起作用。
  4. 属性的 <label> 元素只有在 <input> 元素具有匹配的 id 值时才会起作用。

尝试以下更正 HTML:

<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"> &#060;18:</label> <input class="age" type="number" min="0" max="500" name="age 18"> </td>
            <td><label for="age 24" class="float-left">18-24:</label> <input class="age" type="number" min="0" name="age 24"> </td>
            <td><label for="age 34" class="float-left">25-34:</label> <input class="age" type="number" min="0" name="age 34"> </td>
            <td><label for="age 44" class="float-left">35-44:</label> <input class="age" type="number" min="0" name="age 44"> </td>
        </tr>
</table>