jQuery Bootstrap Select2插件问题与Validate插件 [英] Jquery bootstrap select2 plugin issue with validate plugin
问题描述
在我的引导项目中,我试图使用插件select2,但我意识到 如果您使用此插件,则无法再使用validate插件来验证我的表单中的选择字段. 我会避免使用商业插件引导程序验证器.
In my bootstrap project I'm trying to use the plugin select2 but I realized that if you use this plugin are no longer able to validate select fields in my form with validate plugin. I would avoid using the commercial plugin bootstrap validator..
<div class="container">
<div class="row">
<form id="test_form" action="?">
<div class="col-md-3">
<div class="form-group">
<label for="name">Foo</label>
<select class="form-control" id="foo" name="foo">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="name">Bar</label>
<select class="form-control" id="bar" name="bar">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
<div class="col-md-1">
<button type="submit" class="btn btn-primary">VALIDATE</button>
</div>
</form>
</div>
</div>
JS
/* select 2 plugin */
$('select#foo').select2();
/* Validation */
$("#test_form").validate({
rules:
{
foo: { required: true },
bar: { required: true }
},
errorPlacement: function (error, element) {
$(element).addClass('err');
},
success: function (label, element) {
$(element).removeClass('err');
},
submitHandler: function(form) {
alert("validation ok");
}
});
您认为我该如何解决此问题?谢谢
In your opinion how could I fix this problem? Thanks
推荐答案
好.这是对我有用的东西
Ok. Here is what worked for me
/* select 2 plugin */
$('select#foo').select2();
/* Validation */
$("#test_form").validate({
ignore: 'input[type=hidden]',
rules:
{
foo: { required: true },
bar: { required: true }
},
errorPlacement: function (error, element) {
$(element).parent().addClass('has-error');
},
success: function (label, element) {
$(element).parent().removeClass('has-error');
},
submitHandler: function(form) {
alert("validation ok");
}
});
我添加了一个"ignore:'input [type = hidden]'"选项,因为Select2脚本向原始输入添加了一个隐藏选项,而Jquery Validator似乎忽略了它.然后我将错误类别从元素上的"err"更改为父元素(具有表单组类的div)上的"has-error"
I added a "ignore: 'input[type=hidden]'," option because the Select2 script adds a hidden option to the original input and the Jquery Validator seems to ignore it. Then i changed the error class from "err" on the element to "has-error" on the parent element (the div with form-group class)
这篇关于jQuery Bootstrap Select2插件问题与Validate插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!