问题描述
以下是示例图片:
有两个问题:
这是我的验证表单的代码:
$("#systemcodeForm").validate({
submitHandler: function (form) {
},rules: {
systemtype: {
required: true
}
},messages: {
systemtype: {
required: "Please choose the system type",}
},errorPlacement: function(label,element) {
if(element.hasClass('web-select2') && element.next('.select2-container').length) {
label.insertAfter(element.next('.select2-container'));
}
else{
label.addClass('mt-2 text-danger');
label.insertAfter(element);
}
},highlight: function(element) {
$(element).parent().addClass('has-danger')
$(element).addClass('form-control-danger')
},success: function(label,element) {
$(element).parent().removeClass('has-danger')
$(element).removeClass('form-control-danger')
label.remove();
}
});
这是我的HTML代码:
<form class="cmxform" id="systemrightsForm" method="post" action="#">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">System Type</label>
<select id="systemtype" name="systemtype" class="web-select2 form-control" data-width="100%">
<option value="">-- SELECT SYstem TYPE --</option>
<option value="1">Option 1</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label" for="systemcode">System Code</label>
<input type="text" class="form-control" id="systemcode" name="systemcode" placeholder="Enter system code" autocomplete="off" maxlength="15">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label" for="systemdesc">Description</label>
<input type="text" class="form-control" id="systemdesc" name="systemdesc" placeholder="Enter system description" autocomplete="off" maxlength="40">
</div>
</div>
</div>
</form>
解决方法
您只需使用本机select2
change函数即可在选择选项中监视change
。
在使用jQuery
时,请验证validate
的选择输入,因此默认情况下.validate
在选择option
后不会隐藏标签。
为了获得正确的label
,我们需要使用global variable
来存储标签元素,然后在选择{{1}时使用remove
来存储label
}。
实时工作演示:(两个问题均已解决)
option
var mySelect2 = $('#systemtype')
//initiate select
mySelect2.select2();
//global var for select 2 label
var select2label
$("#systemrightsForm").validate({
rules: {
systemtype: {
required: true
},systemcode: {
required: true
},systemdesc: {
required: true
}
},messages: {
systemtype: {
required: "Please choose the system type",},errorPlacement: function(label,element) {
if (element.hasClass('web-select2')) {
label.insertAfter(element.next('.select2-container')).addClass('mt-2 text-danger');
select2label = label
} else {
label.addClass('mt-2 text-danger');
label.insertAfter(element);
}
},highlight: function(element) {
$(element).parent().addClass('is-invalid')
$(element).addClass('form-control-danger')
},success: function(label,element) {
$(element).parent().removeClass('is-invalid')
$(element).removeClass('form-control-danger')
label.remove();
},submitHandler: function(form) {
},});
//watch the change on select
mySelect2.on("change",function(e) {
select2label.remove(); //remove label
});