我正在使用基础zurb来验证来自客户端的输入。我有4个输入字段通过js验证。我在提交按钮单击后使用jquery来计算.error
,但我收到了意外的值。点击两次“提交”按钮后,即使只有4个.errors
字段,8
的数量也会显示为.errors
。如何显示表单中可见的.errors
个数? LINK
<script>
var $error_items = 0;
$("#submit").click(function(e){
$error_items = $(".error").length;
alert($error_items);
});
</script>
HMTL
<form data-abide>
<div class="name-field">
<label>Your name <small>required</small>
<input type="text" required pattern="[a-zA-Z]+">
</label>
<small class="error">Name is required and must be a string.</small>
</div>
<div class="name-field">
<label>User name <small>required</small>
<input type="text" name="users_name" required pattern="[a-zA-Z]+">
</label>
<small class="error">Username is required and must be a string.</small>
</div>
<div class="email-field">
<label>Email <small>required</small>
<input type="email" required>
</label>
<small class="error">An email address is required.</small>
</div>
<div class="password-field">
<label>Password <small>required</small>
<input type="password" id="password" required pattern="password">
</label>
<small class="error">Your password must match the requirements</small>
</div>
<button type="submit" id="submit">Submit</button>
</form>
答案 0 :(得分:1)
如果在单击“提交”按钮后检查DOM,则会看到每个错误标签的以下内容:
<label class="error"></label>
<small class="error"></small>
最初由您添加,另一个在单击提交按钮后动态添加。 8的计数是正确的。
您可能只想计算label.error
,因为这似乎是您想要计算的内容。
答案 1 :(得分:0)
例如,您可以使用visible selector仅计算可见错误标签:
$('small.error:visible').length