Search code examples
twitter-bootstrap-3jquery-validatedatatablespopoverdatatables-1.10

Submit checkboxes with "Check All" button and clear validation error


Through much trial and error (mostly error), I have managed to incorporate jQuery Validate, Bootstrap 3 (using Popovers for validation messages), and DataTables to create I suspect a fairly common scenario:

A DataTable that contains a column of checkboxes, and offer a "check all" checkbox that selects all the checkboxes across pagination and filtering in a DataTable, and apply jQuery Validate to ensure a user doesn't submit without choosing at least one checkbox.

Here's a link to a live example of what I'm doing: http://live.datatables.net/lomelono/2/

It works (the script picks up all the checked checkboxes (either via the check all checkbox, or if manually chosen, and across pagination and filtering on the DataTable), and will validate if no checkbox is chosen.

What it doesn't do is:

  • Clear the validation error if the check all checkbox is chosen

Another odd side effect by using .appendTo() to ensure all checked checkboxes across pagination/filtering are chosen for submit is all the checkboxes (checked or unchecked) will appear at the bottom of the form before submit (the submit is disabled on the example so you can see the behavior).

Obviously I know just enough jQuery to be dangerous, but is there a better way to submit all the checked checkboxes, AND ensure client-side validation works correctly? Of course, I have a server-side catch, but ideally we want to inform the user BEFORE they submit.

I think I am really close to solving this, and hopefully someone can point me towards the finish line, that will hopefully benefit others who have this kind or similar sort of scenario.


Solution

  • SOLUTION

    You may need to turn those <input type="checkbox"> that are checked and don't exist in DOM into <input type="hidden"> upon form submission.

    For example:

    $("#emailCompose").validate({
        submitHandler: function(form) {
    
           // Iterate over all checkboxes in the table
           table.$('input[type="checkbox"]').each(function(){
              // If checkbox doesn't exist in DOM
              if(!$.contains(document, this)){
                 // If checkbox is checked
                 if(this.checked){
                    // Create a hidden element 
                    $(form).append(
                       $('<input>')
                          .attr('type', 'hidden')
                          .attr('name', this.name)
                          .val(this.value)
                    );
                 }
              } 
           });          
        //form.submit();
        },
    
        // ... skipped ...
    });
    

    DEMO

    See jQuery DataTables: How to submit all pages form data for more details and demonstration.