jqueryformsserializearray

$.serializeArray() not including all the fields of within form


I'm having multiple <form> on single page, all having unique IDs, and the form body is something like below.

<form id="form-main">
    <table>
        <tr>
           <td><input type="text" name="field1"/></td>
                . . . . . . .
                . . . . . . .
        </tr>
    </table>
    <table>
        <tr>
           <td><input type="text" name="field2"/></td>
                . . . . . . .
                . . . . . . .
        </tr>
    </table>     
</form>

<form id="form-second">
    <table>
        <tr>
           <td><input type="text" name="field3"/></td>
                . . . . . . .
                . . . . . . .
        </tr>
    </table>
    <table>
        <tr>
           <td><input type="text" name="field4"/></td>
                . . . . . . .
                . . . . . . .
        </tr>
    </table>
</form>

I know it is not recommended to use tables for having aligned form fields and one can do this with CSS, but actual problem is that when I use $("#form-main").serializeArray, I should get all the fields of this form in my array object, but here I'm getting only fields of first table within the form, rest of the inputs are simply ignored.

Is this a valid behaviour of serializeArray() ? or my use of tables is the real issue? I can use divs instead of tables, but that'd be my last option. Also, in those multiple forms, first table is having fields which are mandatory to fill, so along with "validate-as-you-type" approach, I'm iterating over those mandatory fields to check that they are not left empty, so is that a reason why only first table of each form is included in array object.


Solution

  • This is a perfectly valid use of serializeArray and it should work with multiple elements with the same name as well. I just did a quick test (http://jsfiddle.net/Q5s5V/) and everything behaved as expected... I think there is something else wrong in your code.

    One thing you could try is selecting the inputs themselves rather than the form and see 1) do you have all the inputs you are expecting and 2) does that collection serialize properly.

    var $elements = $('#form-main :input');
    console.log($elements.length);
    console.log($elements.serializeArray());
    

    My guess is that there is a markup error (unclosed tag or whatever) that is preventing those elements from being selected.