So I have a form like this:
<form>
<input name="name" value="A. Hitchcock">
<input name="email" value="[email protected]">
<input name="name" value="Q. Tarantino">
<input name="email" value="[email protected]">
...
</form>
Very simple one. It allow me to get name
and email
from my customers. With jQuery I have a button to allowing me to add more customers (name
and email
) to my form.
I need to echo these datas on each form changes, so I used this code:
$('.form-horizontal').on('change','input', function(){
var dataArray = $('#list-items').serializeArray();
});
With serializeArray()
I can serialize all my datas into an array.
My problem is to show these datas like this using this serializeArray()
:
A. Hitchcock
has this email address : [email protected]
.Q. Tarantino
has this email address : [email protected]
.Any help on how to do this please ?
Would suggest you wrap the pairs in a parent and ignore using serializeArray()
<form>
<div class="person">
<input name="name[]" value="A. Hitchcock">
<input name="email[]" value="[email protected]">
</div>
<div class="person">
<input name="name[]" value="Q. Tarantino">
<input name="email[]" value="[email protected]">
</div>
</form>
Then map the values from the groups:
var res = $('.person').map(function () {
var $inputs = $(this).find('input');
return '<li>' + $inputs.eq(0).val() + ' has this email address :' + $inputs.eq(1).val() + '</li>'
}).get();
$('#list').append(res.join(''));
The objects created by serializeArray() would look like:
[{
"name": "name[]",
"value": "A. Hitchcock"
}, {
"name": "email[]",
"value": "[email protected]"
}, {
"name": "name[]",
"value": "Q. Tarantino"
}, {
"name": "email[]",
"value": "[email protected]"
}]
So parsing those would still require pairing indices to get the name and email anyaway
If you really wanted to do it you could use a for
loop:
var res= [];
for( var i=0; i< arr.length; i=i+2){
res.push('<li>' + arr[i].value + ' has this email address :' + arr[i+1].value + '</li>');
}