forms - How can I validate select2 elements with using jquery validation plugin? -


i use select2 3.5.2 , jquery validation 1.13.1 .i add error class select2 elements using validation plugin "highlight" method when select value can't remove error class. how can solve this?

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, errorclass, validclass) {         var elem = $(element);              if(elem.hasclass('sl')) {                 elem.siblings('.sl').find('.select2-choice').removeclass(errorclass);             } else {                 elem.removeclass(errorclass);             }         }     });  }); 

https://jsfiddle.net/8lyfa3k2/6/

since original select elements hidden select2 plugin, jquery validate plugin can no longer find triggering events automatically fire validation when value changed.

you have create custom handler programmatically trigger validation, using .valid() method, whenever value changes...

$('select').on('change', function() {  // when value changes     $(this).valid(); // trigger validation on element }); 

demo: https://jsfiddle.net/8lyfa3k2/4/


your unhighlight function apparently broken. seems work better...

unhighlight: function (element, errorclass, validclass) {     var elem = $(element);     elem.removeclass(errorclass); } 

demo 2: https://jsfiddle.net/8lyfa3k2/5/


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -