[英]Clear jquery.validate error messages on change/hide of disabled attributes
使用jquery.validate在表单上启用和禁用禁用字段时,尝试清除错误消息。 现在,我可以在显示更改或单击字段并从禁用更改道具的地方工作。 因此,它可以满足我的需求,即隐藏不必要的字段,并且在它们处于禁用状态时不对其进行验证。 但是,当我将这些字段切换回其禁用状态并隐藏它们时,错误消息仍会显示,直到再次单击“提交”为止。 我尝试将.valid()调用添加到toggleDisabled函数,并且当它们返回到隐藏/禁用状态时,它不会使消息消失。 有人看到可以添加哪些内容来使字段消失时消息消失吗?
这是到目前为止我正在使用的小提琴: JS小提琴
我正在从使用jquery.validate:
HTML:
<form id="myform">
<input type="text" name="field1" />
<br/>
<br />
<input type="text" id="toggleInput" name="toggleInputName" disabled style="display:none" />
<input type="button" id="toggleButton" value="Toggle Disabled" />
<div id="tickets">
<label for="group1">Number of Tickets: <span class="req">*</span></label>
<select class="group1_dropdown" id="group1" name="group1">
<option value="0">-- Please select --</option>
<option value="1">Member</option>
<option value="2">Member + 1 Guest</option>
<option value="3">Member + 2 Guests</option>
<option value="4">Member + 3 Guests</option>
</select>
</div>
<input type="text" id="payMethod" name="payMethodName" disabled style="display:none" />
<input type="submit" />
</form>
JS:
$(document).ready(function () {
$('#myform').validate({
onblur: true,
onkeyup: false,
ignore: ":disabled",
rules: {
field1: {
required: true,
minlength: 5
},
payMethodName: {
required: true,
minlength: 5
},
toggleInputName: {
required: true,
minlength: 5
}
},
submitHandler: function (form) { // for demo
alert('valid form');
return false;
}
});
});
//used for toggling/showing disabled fields - will display and make not disabled on same click event
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this);
if ($this.prop('disabled')) {
$this.prop('disabled', false).show();
} else {
$this.prop('disabled', true).hide();
}
});
};
})(jQuery);
$(function () {
$('#toggleButton').click(function () {
$('#toggleInput').toggleDisabled();
});
});
$(function () {
$("#group1").change(function () {
var str = "";
str = parseInt($(this).val());
if(str == 2)
$("#payMethod").toggleDisabled();
else
$("#payMethod").toggleDisabled();
});
});
我对您的插件做了一些更改,以完成您想要的操作。
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this),
id = $this.attr('id'), //get the id of input
label = $this.next('label[for="' + id + '"]'); //find the next label which is added by jQuery Validator
if ($this.prop('disabled')) {
label.show(); //show the label
$this.prop('disabled', false).show();
} else {
label.hide();//hide the label
$this.prop('disabled', true).hide();
}
});
};
})(jQuery);
无需更改插件的另一种方法
$(document).ready(function () { //place your all DOM ready code in one DOM ready handler var validator = $('#myform').validate({ //assign validate to a variable //validator code here }); $('#toggleButton').click(function () { validator.resetForm();//reset Form validation $('#toggleInput').toggleDisabled(); }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.