我使用select2 3.5.2和
jquery验证1.13.1.我可以使用验证插件“highlight”方法为select2元素添加错误类,但是当我选择一个值时,我无法删除该错误类.我怎么解决这个问题?
HTML
<form id="test" class="frm"> <div> <input type="text" name="name" /> </div> <div> <label for="singleselect"></label> <select class="sl" id="singleselect" name="singleselect"> <option></option> <option value="val1">Val-1</option> <option value="val2">Val-2</option> </select> </div> <div> <label for="multipleselect"></label> <select class="sl" id="multipleselect" name="multipleselect" multiple="multiple"> <option></option> <option value="val1">Val-1</option> <option value="val2">Val-2</option> </select> </div> <button class="btn">Submit</button> </form>
JS
$(document).ready(function () { $('.sl').select2({ placeholder:'Select' }) $.validator.setDefaults({ ignore: [] }); $('#test').validate({ errorElement: 'span',errorClass: 'error',rules: { singleselect:'required',multipleselect:'required',name:'required' },highlight: function (element,errorClass,validClass) { var elem = $(element); elem.addClass(errorClass); },unhighlight: function (element,validClass) { var elem = $(element); if(elem.hasClass('sl')) { elem.siblings('.sl').find('.select2-choice').removeClass(errorClass); } else { elem.removeClass(errorClass); } } }); });
解决方法
由于原始选择元素被Select2插件隐藏,因此jQuery Validate插件无法再找到任何触发事件,以便在更改值时自动触发验证.
您只需创建一个自定义处理程序,以编程方式触发验证,使用.valid()方法,只要值更改…
$('select').on('change',function() { // when the value changes $(this).valid(); // trigger validation on this element });
演示:https://jsfiddle.net/8Lyfa3k2/4/
你的unhighlight功能显然被打破了.这看起来效果更好……
unhighlight: function (element,validClass) { var elem = $(element); elem.removeClass(errorClass); }