JQuery Require Checkbox and Radio Button before submit

后端 未结 3 1099
小鲜肉
小鲜肉 2021-01-31 22:29

I am having one heck of a hard time trying to figure this out. Been looking at examples and tools for JQuery validation for over 3 hours now.

All I want to do is require

相关标签:
3条回答
  • 2021-01-31 23:06

    This worked for me in my case where I want to require users to check a checkbox in order to submit a form.

    $(document).ready(function(){
            $('#yourinput').required = true;
    });
    
    0 讨论(0)
  • 2021-01-31 23:24
    $('#form1').submit(function(){
        if ($(':checkbox:checked', this)[0] && $(':radio:checked', this)[0]) {
            // everything's fine...
        } else {
            alert('Please select something!');
            return false;
        }
    });
    
    0 讨论(0)
  • 2021-01-31 23:25

    To do this you have to use the :checked selector. Although JP's answer is fine, I'd probably do this:

    $('#form1').submit(function() {
        if ($('input:checkbox', this).is(':checked') &&
            $('input:radio', this).is(':checked')) {
            // everything's fine...
        } else {
            alert('Please select something!');
            return false;
        }
    });
    

    Couple of notes:

    • I think it reads better to use the is function, which returns a boolean of the selector.
    • You can use :radio and :checkbox as a shortcut for selecting all radios and checkboxes in a form. However, according to the jQuery manual, it is bad practice to use these selectors without specifying input before them, as they evaluate to *:checkbox and *:radio otherwise, which are very slow selectors.
    • By passing this as the second argument we are specifying a context for the search, and thus are only searching for checkboxes and radio inputs inside the current form. Without it we might get false positives if there happens to be another form in the page.
    0 讨论(0)
提交回复
热议问题