如果复选框组中未选中任何复选框,则显示错误 [英] Display error if no checkbox is checked in checkbox group

查看:146
本文介绍了如果复选框组中未选中任何复选框,则显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在同一复选框组中未选中任何复选框时,如何使用Foundation 5的Abide HTML5表单验证库显示错误消息?

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?

推荐答案

您必须编写自己的遵守验证程序,但这非常简单.

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

工作示例: CodePen链接

JavaScript

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>

这篇关于如果复选框组中未选中任何复选框,则显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆