Reputation: 2348
I have a form that contains an n amount divs each of wich contain individual inputs. These divs exist under the same class name "c1", but do not contain any other attributes. Each c1 contains the same inputs with unique class names. Each div will always contain the same style of inputs. An example of this would be:
<div class="c1">
<input class="in1" type="text"/>
<input class="in2" type="text"/>
</div>
<div class="c1">
<input class="in1" type="text"/>
<input class="in2" type="text"/>
</div>
<div class="c1">
<input class="in1" type="text"/>
<input class="in2" type="text"/>
</div>
The information should be sent via a post using jQuery's $.post(...). I do not use an id system for the users ability to modify the content, ie adding and removing the c1 divs. I am not sure how to post the gathered information to a php page for an n amount of items, nor to keep the information together based on the divs. Any advice?
I have been considering using serialize, but I am not sure how to keep the information unique based on the encapsulated div. An alternative is to make a custom map
for the post's "data" argument using the .each
command to iterate through each div, but something tells me that I am heading down the wrong path.
Upvotes: 0
Views: 98
Reputation: 1033
If you generate it dynamically, you could set an unique id for each input. Like inp1, inp2 and so on. Then you could create your map based on those unique ids.
Upvotes: 0
Reputation: 75083
If you are strict to follow your HTML code, there is nothing you can do automatically, like use the .serialize()
method from jQuery as it needs at least the name
to be used.
Doing it manually, you could create the data and then post it like:
$("#btnSave").click(function() {
var dt = {},
div = 0,
arr = 0;
$(".c1").each(function() {
// for each <div class="c1">
$(this).find("input").each(function() {
// for each <input> inside the <div>
dt['p' + arr++] = 'd' + div +
'_c_' + $(this).attr("class") +
'_v_' + $(this).val();
});
div++;
});
// now, we post the data
$.post("http://bing.com/", dt, function(data) {
// do something...
});
return false; // dont post automatically
});
and then you have something like:
p0 _d_0_c_in1_v_1
p1 _d_0_c_in2_v_4
p2 _d_1_c_in1_v_2
p3 _d_1_c_in2_v_5
p4 _d_2_c_in1_v_3
p5 _d_2_c_in2_v_6
and from d2_c_in2_v_6
you can split the string in:
_d_
for div_c_
for class name_v_
for input valueUpvotes: 0
Reputation: 25159
You could do something like this to autogenerate named parameters:
var postData = {};
$(".c1").each(function() {
var name = "input" + $(this).index();
postData[name + "in1"] = $(this).find(".in1").val();
postData[name + "in2"] = $(this).find(".in2").val()
})
console.log(postData);
And then just submit the postData via AJAX
Upvotes: 1