Display error if no checkbox is checked in checkbox group

余生颓废 提交于 2019-12-06 08:02:52

问题


How do I display an error message with Foundation 5's Abide HTML5 form validation library when no checkboxes are checked within the same checkbox group?


回答1:


You have to write your own abide validator, but it is quite simple.

Working example: CodePen link

JavaScript

$(document).foundation({
    abide: {
        validators: {
            checkbox_limit: function(el, required, parent) {
                var group = parent.closest('.checkbox-group');
                var min = group.attr('data-abide-validator-min');
                var checked = group.find(':checked').length;
                if (checked >= min) {
                    group.find('small.error').hide();
                    return true;
                } else {
                    group.find('small.error').css({
                        display: 'block'
                    });
                    return false;
                }
            }
        }
    }
});

HTML

<form data-abide>
   <div class="row">
      <div class="small-12 column">
         <h4>Select your favourite vehicles</h4>
      </div>
   </div>
   <div class="row">
      <div class="small-12 columns checkbox-group" data-abide-validator-min="1">
         <label>
            <input type="checkbox" data-abide-validator="checkbox_limit" value="car" />
            car
         </label>
         <label>
            <input type="checkbox" data-abide-validator="checkbox_limit" value="train" />
           train
         </label>
         <label>
            <input type="checkbox" data-abide-validator="checkbox_limit" value="bicycle" />
            bicycle
         </label>
         <label>
            <input type="checkbox" data-abide-validator="checkbox_limit" value="ferry" />
            ferry
         </label>
         <label>
            <input type="checkbox" data-abide-validator="checkbox_limit" value="plane" />
            plane
         </label>
         <small class="error">You have to check at least one vehicle.</small>
      </div>
   </div>
   <div class="row">
      <div class="small-12 columns">
         <button type="submit">Submit</button>
      </div>
   </div>
</form>


来源:https://stackoverflow.com/questions/26890023/display-error-if-no-checkbox-is-checked-in-checkbox-group

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