Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that a form has AT LEAST one field filled in

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.

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?

like image 222
Tom Perkins Avatar asked Dec 11 '22 23:12

Tom Perkins


2 Answers

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
    });
});​

Here is a demo:

--- jsFiddle DEMO ---

like image 66
jackwanders Avatar answered Feb 15 '23 10:02

jackwanders


//select all text inputs in form and filter them based on...
var isFilled = $('input[type="text"]', 'form').filter(function() {
    return $.trim(this.value).length;  //text inputs have a value
}).length;                             //get the selector length

//if selector contains at least one filled in text input, submit form
if (isFilled) {..submit form..} 
like image 45
adeneo Avatar answered Feb 15 '23 09:02

adeneo