How to validate a form with multiple checkboxes to have atleast one checked

前端 未结 11 807
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 23:40

I\'m trying to validate a form using the validate plugin for jquery. I want to require that the user check at least one checkbox in a group in order for the form to be sub

11条回答
  •  生来不讨喜
    2020-11-30 23:59

    This script below should put you on the right track perhaps?

    You can keep this html the same (though I changed the method to POST):

    zero
    one
    two

    and this javascript validates

    function onSubmit() 
    { 
        var fields = $("input[name='list']").serializeArray(); 
        if (fields.length === 0) 
        { 
            alert('nothing selected'); 
            // cancel submit
            return false;
        } 
        else 
        { 
            alert(fields.length + " items selected"); 
        }
    }
    
    // register event on form, not submit button
    $('#subscribeForm').submit(onSubmit)
    

    and you can find a working example of it here

    UPDATE (Oct 2012)
    Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.

    UPDATE (May 2013)
    Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)

    UPDATE (June 2016)
    Changes == to ===

提交回复
热议问题