我正在使用 Jquery Validate在我的网络表单中。我有一个空输入,但是单击按钮时输入会动态填充文本。当我这样做时,验证似乎不起作用。
- 当输入为空时,提交验证有效(输入变为红色)。
- 当动态填充输入时,它保持红色,应该变成绿色
我的代码在下面,这是一个 fiddle ;
在 fiddle 中,当输入为空时单击提交,然后将按钮切换到 No
- 输入应更改为绿色,而无需再次提交表单。
HTML
<p>Does this item have an inventory number?</p>
<p>
<form id="myForm" method="post">
<input type="checkbox" class="input-large" value='1' name="btn" id="btn">
<div class="control-group">
<div class="controls">
<div class="input-prepend">
<input type="text" class="input-large" id="type" name="type" placeholder="Inventory Number">
</div>
</div>
</div>
<input type="submit" class="submit" value="Submit">
</form>
Jquery
$(function() {
$('#btn').bootstrapToggle({
on: 'No',
off: 'Yes',
onstyle: 'danger'
});
})
$("#myForm").validate({
rules: {
type: {
required: true,
minlength: 2
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
unhighlight: function(label) {
$(label).closest('.control-group').addClass('success');
},
});
$("#btn").on("change", function() {
if ($(this).prop('checked') == true) {
$("#type").attr("readonly", "true");
$("#type").val("Personal Item");
$("#type").rules("remove", "number minlength maxlength");
}
if ($(this).prop('checked') == false) {
$("#type").removeAttr("readonly");
$("#type").val("");
$("#type").rules("add", {
required: true,
minlength: 5,
maxlength: 6
});
}
});
最佳答案
您在 control-group
上使用了一些自定义的 highlight
和 unhighlight
。
只需将此添加到 checked==true
条件:
$("#type").closest('.control-group').removeClass("error").addClass("valid");
$("#type").next(".error").remove();
由于删除了规则,因此不会重新验证...
你的 Fiddle updated .
关于javascript - JQuery 验证按钮切换上的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51898622/