jQuery Validation plugin - validate a mix of radio and checkbox inputs with Bootstrap 3

scharfmn

On $(document).ready, the submit button is disabled. The button should be enabled only when the entire form is valid, i.e. 1) one radio (fruit) is selected, and 2) one or more checkboxes (occasions) are selected. I have looked at many answers here, and tried using function that tests if (form.valid()) on document change, but that evaluates to true when only the fruit is selected. I believe that the submitHandler is what I want to get at the whole form, but it's not firing. Changing the radios into checkboxes doesn't make a difference.

jsFiddle

html

<form id="categorizer-form" method="POST" action="\submit">
    <div class="container">
        <br><p>1. What <strong>kind</strong> of fruit is this?</p>
        <div class="btn-group col-xs-12" data-toggle="buttons">
            <label class="btn btn-default">
                <input type="radio" name="kind" id="apple" value="apple">apple
            </label>
            <label class="btn btn-default">
                <input type="radio" name="kind" id="orange" value="orange">orange
            </label>
        </div>
    </div>

    <div class="container">
        <br><p>2. On what <strong>meal occasions</strong> would you eat it? (Please choose as many as apply.)</p>
        <div class="btn-group col-xs-12" data-toggle="buttons">
            <label class="btn btn-default">
                <input type="checkbox" name="occasion" id="breakfast" value="breakfast" >breakfast
            </label>
            <label class="btn btn-default">
                <input type="checkbox" name="occasion" id="lunch" value="lunch" >lunch
            </label>
            <label class="btn btn-default">
                <input type="checkbox" name="occasion" id="dinner" value="dinner" >dinner
            </label>
            <label class="btn btn-default">
                <input type="checkbox" name="occasion" id="snack" value="snack" >snack
            </label>
        </div>
    </div>
    <!-- ######################### -->
<br>
<br>
    <div class="well well2">
        <div class="container">
            <div class="row">
                <div class="col-xs-12 text-center">
                    <button class='btn btn-lg btn-danger btn-next' type='submit' id='Next'>Click to submit</button>
                </div>
            </div>
        </div>
    </div>
</form>

js

$(document).ready(function() {

    $('.btn-next').attr('disabled', true)

    $( 'form#categorizer-form' ).validate({
        debug: true,
        rules: {
            kind: {
                required: true,
            },
            occasion: {
                required: true,
            }
        },

        submitHandler: function(form) {
            alert('submitHandler fired')
            $('.btn-next').prop('disabled', false).removeClass('btn-danger').addClass('btn-success');        // enables button
        }

    });

});
Sparky

Your code...

submitHandler: function (form) {
    alert('submitted')
    $('.btn-next').prop('disabled', false).removeClass('btn-danger').addClass('btn-success'); // enables button
}

The submitHandler will only fire when both of these conditions are met...

  1. The user clicks the submit button.

  2. The form is valid.

Your submitHandler is not firing because your submit button is disabled and cannot be clicked. You cannot enable the submit button within the submitHandler because you have no way to trigger it without clicking the button.

Instead, you must enable the submit button outside of the submitHandler by using a change event handler, external to the .validate() method, that fires every time the form changes. Then you can use the .valid() method to test the form and decide if the button can be enabled.

$('#categorizer-form').on('change', function () {
    if ($(this).valid()) {
        // enable button
        $('.btn-next').prop('disabled', false).removeClass('btn-danger').addClass('btn-success'); 
    } else {
        // disable button        
        $('.btn-next').prop('disabled', true).addClass('btn-danger').removeClass('btn-success'); 
    }
});

DEMO: http://jsfiddle.net/h1r2fmj0/


Quote OP:

"... tried using function that tests if (form.valid()) on document change, but that evaluates to true when only the fruit is selected."

That is impossible, unless you somehow attached .valid() to the fruit field. Otherwise, when properly attached to the <form> element, .valid() can only return true when the whole form is valid.

In other words, form.valid() is meaningless, unless you've already defined var form = $('#categorizer-form').

It must be attached to a variable or selector that targets the <form> element. Depending on how/where you used it, the form keyword may not work. (The form keyword is only for use inside of certain callback functions like submitHandler. However, you normally would not use the .valid() method anywhere inside of the .validate() method.)

Notice in the demo code above where $(this).valid() is the same as $('#categorizer-form').valid(), because $(this) represents $('#categorizer-form').


You need to show us the code that is causing the problem you describe.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

My JQuery validation plugin behaves strangely with checkbox inputs

multiple jQuery validation bootstrap plugin do not validate multiple forms

URL validation with jQuery validate plugin

jquery validation is not working with validate plugin

Bootstrap with jQuery Validation Plugin

jQuery Validation plugin errorPlacement for checkbox

How to validate array of inputs using validate plugin jquery

jQuery Validation onfocusout error message for Radio & Checkbox

jQuery validation plugin and Bootstrap 4

Bootstrap 4 and jQuery Validation Plugin

Validate date and datetime with Bootstrap datetime picker, Jquery validation plugin in an Asp.Net MVC4 application

Jquery validation plugin - TypeError: $(...).validate is not a function

Validate dependent select options with jQuery Validation plugin

jQuery checkbox validation not working inside bootstrap modal

Style all Inputs but checkbox and radio

JQuery Validate Form Inputs & Highlight Labels with Bootstrap 4

jQuery-Form-Validator plugin: how to validate one single checkbox

Remove 'required' from checkbox when an input is filled with jQuery Validate plugin

jquery validate plugin if checkbox is checked textarea cannot be empty

Bootstrap select Plugin Not work With jQuery Validation

Bootstrap 3 JQuery Validation not working

ASP.NET MVC with JQuery, JQuery Validate & bootstrap, validation inconveniences

Do you have to use JQuery Validation Plugin validate() on a form element?

jQuery Validation Plugin: validate decimal number with comma as decimal separator

How to validate input fields with a dot in name using the jquery validation plugin?

How can I validate a regular expression using jQuery Validation plugin?

How to delay validation for jquery validate plugin for on key up event?

Bootstrap 3 validation states with JQuery-validated form that uses Chosen plugin

Validation and compare inputs with jQuery?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  7. 7

    Do Idle Snowflake Connections Use Cloud Services Credits?

  8. 8

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  9. 9

    Binding element 'string' implicitly has an 'any' type

  10. 10

    BigQuery - concatenate ignoring NULL

  11. 11

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  12. 12

    In Skype, how to block "User requests your details"?

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Pandas - check if dataframe has negative value in any column

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Generate random UUIDv4 with Elm

  17. 17

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  18. 18

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  19. 19

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  20. 20

    EXCEL: Find sum of values in one column with criteria from other column

  21. 21

    How to use merge windows unallocated space into Ubuntu using GParted?

HotTag

Archive