macek/jquery-serialize-object

parsing array of fields

antonioaltamura opened this issue · 2 comments

This is my form

<form id="tA">
 <select class="form-control " name="array[][id]"id="fundamentalrights" data-select="mysettings"></select>
 <input type="text" name="array[][comment]" class="form-control" />
</form>

$('form#tA').serializeObject() works fine and builds the obj this way

{
array:[
{"id":"#ID","comment":"mycomments"}
]
}

the problem is #ID is wrong because the select is a select2 element.
So I have to replace the array[0][id] value with its select2 value: $(selector).select2('data');

this code obiouvsly break the array structure made by jquery-serialize-object

        var form = $('form#tA').serializeObject()
        $('[data-select]').each(function() {
           var name =  $(this).attr('name');
           form[name] = $(this).select2('data');
        });

printing this

{
array[][id]:#CORRECT ID VALUE
array[][comment]:"mycomments"
}

maybe you have a correct way to keep the array structure?
Basically I need a re-serialization after those edits

macek commented

Your question isn't very clear, but it seems like you're trying to group values together for a dynamic-length form

<input name="array[][id]" value="1">
<input name="array[][comment]" value="2">

Because you're using the "push" style key ([]), your output will look like

{
  "array": [
    {"id": "1"},
    {"comment": "2"}
  ]
}

If you intend to keep these values together, you have to manually specify indexes

<!-- note the use of 0 here -->
<input name="array[0][id]" value="1">
<input name="array[0][comment]" value="2">

<!-- note the use of 1 here -->
<input name="array[1][id]" value="a">
<input name="array[1][comment]" value="b">

<!-- use 2, 3, 4... so on -->

Will result in

{
  "array": [
    {
      "id": "1",
      "comment": "2"
    },
    {
      "id": "a",
      "comment": "b"
    }
  ]
}

PS don't name your inputs things like "array"

the real name isn't array :)
thanks

please note your serializeObject() method works like a charm with array[][id] and array[][comment].
The problems comes when I want to manually replace their values (and that's the problem I was talking about in first post explained in two words)
This is the serializeObject() result
el

of this form

<input name="horizontalprovisions[][id]" value="..">
<input name="horizontalprovisions[][comment]" value="..">
<input name="horizontalprovisions[][id]" value="...">
<input name="horizontalprovisions[][comment]" value="...">

Also, I have several array like this in my form, I can't think currently a way to generalize a dynamic counter :(
Beside even with a counter $.each() won't work neither.
The problem stays the access of a value of a nested fields after serializeObject