[英]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"> <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有一些錯誤:
<input>
元素需要添加class="age"
,以便由$(".age:input").each()
函數識別。 name
的第二<input>
元素缺少閉雙引號( "
)。 oninput
事件中的calcage
調用之后,您缺少括號( ()
)。 但是,由於您正在使用$(".age").change()
函數來調用calcage()
函數,因此也不必使oninput
事件也可以調用calcage()
函數。 此外,每次輸入發生更改時,都會調用oninput
事件,而無需等待所有更改完成。 這意味着,如果學生輸入的年齡為“ 30”,則calcage
功能將被調用兩次:首先輸入“ 3”,然后再次輸入“ 0”。 由於這不是您想要的,因此可以從輸入中刪除那些事件處理程序。 保留$(".age").change()
因為這只會在學生完成鍵入后才會觸發。 一旦您的<input>
元素添加了class="age"
,它將起作用。 <label>
元素僅在存在具有匹配id
值的<input>
元素時才起作用。 嘗試使用以下更正的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"> <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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.