我正在尝试使用 jQuery 中的 .each() 方法构建一个函数,该函数扫描空输入字段,以红色突出显示它们,然后提供一条警报消息,让用户知道需要更改哪些内容。
这是我的示例 html:
<tr>
<td><input type="number" class="amount required" name="amount" ></td>
<td><input type="number" class="carrier required" name="carrier" ></td>
<td><input type="number" class="kilo required" name="kilo" ></td>
</tr>
<button type="submit" class="analyze">Analyze</button>
这是循环遍历表数据并添加 CSS 的函数:
$(".analyze").click(function() {
$(".required").each(function() {
if ($(this).val() === "") {
$(this).parents("td").addClass("redClass");
alert("Looks like some of the fields aren't filled out correctly. They're highlighted in red.");
}
});
});
问题在于代码逐一遍历数组并为每个空单元格创建一条警报消息。理想情况下,它会一次性将 .redClass 添加到所有空字段中,并且如果有空字段,则仅在末尾显示一条警报消息。
最佳答案
根据我的评论:
$(".analyze").click(function() {
var counter = 0;
$(".required").each(function() {
if ($(this).val() === "") {
$(this).parents("td").addClass("redClass");
counter++;
}
});
if(counter > 0){
alert("Looks like some of the fields aren't filled out correctly. They're highlighted in red.");
}
});
关于javascript - 使用 .each() 方法验证 jquery 中的表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29551093/