How can I iterate inside elements in JavaScript?
I've those elements:
<div class="row">
<input type="text" class="attributo" name="attributo[7]" value="1">
<input type="text" class="attributo" name="attributo[7]" value="14">
</div>
<div class="row">
<input type="text" class="attributo" name="attributo[4]" value="2">
<input type="text" class="attributo" name="attributo[5]" value="1">
</div>
<div class="row">
<input type="text" class="attributo" name="attributo[4]" value="2">
</div>
and this script to edit form before submit:
$("#form").on("submit", function(e){
e.preventDefault();
var form = $(this);
// i tried this
var rows = $(this).find(".row");
rows.each(function(index, element){
form.append('<input type="hidden" name="row['+index+'][attributi]['+indexAttr+']" value="' + element.value + '" />');
});
// then submit
form.submit();
});
but I don't know how to retrieve indexAttr
that in this case is the number inside attributo[]
, for example, 7
in case of: attributo[7]
My goal is to have a structured array in destination_page.php
like (using my example above):
$post = $_POST['row'];
var_dump($post);
// I NEED THIS
row => array(
0 => array(
"attributi" => array(
7 => 1,
7 => 14
)
),
1 => array(
"attributi" => array(
4 => 2,
5 => 1
)
),
2 => array(
"attributi" => array(
4 => 2
)
)
)
<form id="form" method="post" action="">
<div class="row">
<input type="text" class="attributo" name="attributo[7]" value="1">
<input type="text" class="attributo" name="attributo[7]" value="14">
</div>
<div class="row">
<input type="text" class="attributo" name="attributo[4]" value="2">
<input type="text" class="attributo" name="attributo[5]" value="1">
</div>
<div class="row">
<input type="text" class="attributo" name="attributo[4]" value="2">
</div>
<div class="row">
<button id="save" type="button">save</button>
</div>
</form>
$("#save").on("click", function(e){
var form = $("#form");
// i tried this
var rows = $(form).find(".row");
rows.each(function(index, element){
var input = $(element).find('input');
input.each(function(i, v){
var inputValue = $(v).val();
var inputName = $(v).attr('name');
var matches = inputName.match(/attributo\[(.*?)\]/);
var inputIndex = matches[1];
form.append('<input type="hidden" name="row['+index+'][attributi]['+inputIndex+']" value="' + inputValue + '" />');
});
});
// then submit
form.submit();
});
don't add the hidden fields on submit because it goes into an infinite loop, i've changed your code so it submit when u press the save button i've added to the HTML
also you have a problem in your logic, you can't have an array with the same ID but i'll leave that to you :)