Search code examples
javascriptjqueryonclickprototypejs

Posting an array of checkboxes from an onclick button event prototype or jQuery


I have a table of rows containing data and a checkbox to the very left. Here is the HTML for one of my rows

(the checkbox):

<input type="checkbox" id="records[]" name="records[]" value="1" />

As you can see, the row has a checkbox with a name of "records[]", indicating it is an array of values within the records array. Just above my HTML table, I have a button that when pushed, will take the checked records and post it to a new URL. I cannot figure out how to accomplish this. Just an FYI, the table and the buttons are not within a form.


Solution

  • I'm assuming that your HTML looks something like what is posted below, where your inputs are within the form, but the table and your buttons are not.

    One trick to handling this situation is to bind an onclick event handler to your button element that then invokes the click method of a hidden submit button in the form itself. This effectively "chains" your buttons together.

    <form action="/yourURL" name="yourForm" method="post">
        <input type="checkbox" id="records[]" name="records[]" value="1" />
    
        <input type="submit" style="display:none" id="submitBtn" />
    
    </form>
    
    <table>
        <button id="yourButton" value="click me" />
    
    </table>
    
    $('#yourButton').click(function() {
        $('#submitBtn').click();
    }
    

    Another method is to just call the submit method of the form object itself:

    $('#yourButton').click(function() {
        $('[name="yourForm"]').submit();
    }