如何检查表单至少填写一个字段

Tom*_*ins 3 javascript forms jquery

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

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

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

jac*_*ers 10

下面是应与所有表单字段类型工作的函数:text,select,radio,checkbox,textarea,file,和HTML5输入类型,如email.这个功能使得唯一的假设是,所有的select元素都有optionvalue=""

/**
 * 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
    });
});?
Run Code Online (Sandbox Code Playgroud)

这是一个演示:

--- jsFiddle DEMO ---