Can I combine the validation-error of two Combo box using jquery?

我是研究僧i 提交于 2019-12-13 06:35:30

问题


I am trying to validate 3 combobox which are for date, month, year.

I am using jquery.js and jquery.validate.js. It is showing errors for each combobox if it is not selected, but I want only one message instead of 3 errors.


回答1:


Two things are needed - add all 3 to a group, and setup the errorPlacement option to appropriately place the error message.

So if your form looks like this:

<form>
  <select name="day" class="required">
     <option value="">Day</option>
     <option value="1">1</option>
     <!-- etc -->
  </select>
  <select name="month" class="required">
     <option value="">Month</option>
     <option value="1">Jan</option>
     <!-- etc -->
  </select>
  <select name="year" id="year" class="required">
     <option value="">Year</option>
     <option value="2013">2013</option>
     <!-- etc -->
  </select>
  <br>
  <input type="submit">
</form>

Then you need a jQuery Validate call like this:

$('form').validate({
   groups: {
      myDate: 'day month year'
   },
   errorPlacement: function(error, element) {  
     if (element.attr("name") == "day" 
             || element.attr("name") == "month" 
             || element.attr("name") == "year" )
        error.insertAfter("#year");
     else
        error.insertAfter(element);
   }
});

And if you put that all together you get an example that looks like this: http://jsfiddle.net/ryleyb/Yzdag/



来源:https://stackoverflow.com/questions/17084852/can-i-combine-the-validation-error-of-two-combo-box-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!