如何检查表单至少填写一个字段 [英] How to check that a form has AT LEAST one field filled in

查看:360
本文介绍了如何检查表单至少填写一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正处于构建网站的最后阶段,还剩下一个关键任务:设置一些表单验证,阻止用户提交空白搜索。

I'm in the final stages of building a site and have one key task left: To setup some form validation that stops users being able to submit a blank search.

我知道以下帖子,但发现如何使其工作不清楚,以及如何将其用于下拉列表( jQuery Validate - 要求组中至少有一个字段被填充

I'm aware of the following post, but have found this unclear on how to get it to work, and how to use this for dropdown's (jQuery Validate - require at least one field in a group to be filled)

关于我如何做到这一点的任何想法,或任何可能有用的指南指南都将受到大力赞赏?

Any ideas on how I can do this, or any pointers to a guide that may help, will be massively appreciated?

推荐答案

这是一个应该适用于所有表单字段类型的函数: text select radio 复选框 textarea file 和HTML5输入类型,如 email 。这个函数唯一的假设是所有 select 元素都有选项 value =

Here is a function that should work with all form field types: text, select, radio, checkbox, textarea, file, and HTML5 input types like email. The only assumption this function makes is that all select elements have an option with value=""

/**
 * 1) gather all checkboxes and radio buttons
 * 2) gather all inputs that are not checkboxes or radios, and are not buttons (submit/button/reset)
 * 3) get only those checkboxes and radio buttons that are checked
 * 4) get only those field elements that have a value (spaces get trimmed)
 * 5) if the length of both resulting collections is zero, nothing has been filled out
 */
function checkFields(form) {
    var checks_radios = form.find(':checkbox, :radio'),
        inputs = form.find(':input').not(checks_radios).not('[type="submit"],[type="button"],[type="reset"]'),
        checked = checks_radios.filter(':checked'),
        filled = inputs.filter(function(){
            return $.trim($(this).val()).length > 0;
        });

    if(checked.length + filled.length === 0) {
        return false;
    }

    return true;
}

$(function(){
    $('#myForm').on('submit',function(){
        var oneFilled = checkFields($(this));
        // oneFilled === true if at least one field has a value
    });
});​

这是一个演示:

--- jsFiddle DEMO ---

这篇关于如何检查表单至少填写一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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