form to json error when there is a dynamic list operation

119 views Asked by At

There is a addresses in my APP, there is a button that will add address if neccessary, but when I transfer the form to object and use ajax submit, the form object will only contain the last address. here is the demo

EDIT

this issue has been partial fixed, but we still think about if remove function is added, how we control the index of the list, if anyone has a good idea, you can give me a comment, thanks, and thank for the help from @weeksdev

1

There are 1 answers

1
weeksdev On BEST ANSWER

The issue is that the input objects name is the same for all inputs. Modifying the name to iterate and all inputs show in output. Check this fiddle out for example

Here is the correspoding code with the change:

Option 1:

$(".addAddress").click(function(){
    $("#addressEare").append(' <br><input type="text" readonly="readonly" name="person.addresses.name' + i + '" value="address'+i+'" class="addressName" />');
    i++;
});

Option 2:

If you are looking to get an array of objects with a name property then the corresponding code would be this:

HTML:

<form id="i_form">
    <div id="addressEare" name="">
        <input type="text" readonly="readonly" name="person.addresses[0].name" value="address1" class="addressName" />
    </div>
    <input type="button" value="Add Address" class="addAddress"/>
    <input type="button" value="Show Form Object" class="showFormObj"/>
</form>

JS:

var i=2;
$(".addAddress").click(function(){
    $("#addressEare").append(' <br><input type="text" readonly="readonly" name="person.addresses[' + i + '].name" value="address'+i+'" class="addressName" />');
    i++;
});
$(".showFormObj").click(function(){
    var formObj = form2js("i_form",".");
    alert(JSON.stringify(formObj));
});

Here is fiddle demonstrating option 2