JQuery Dynamic Form - Submitting an input box with the same name
-
14-06-2021 - |
Question
i need help with this. I'am using JQuery's Dynamic Form plug-in, it duplicates my input boxes every time I click the '+' button however, the problem comes when i hit the submit button i cannot retrieve the values of my input boxes through $_POST because they were all of the same 'name'.
How could i change the name of my input boxes when they were duplicated?
HTML:
<div id="duplicate3">
<input id="description" type="text" name = "description"size="40">
<input id="amount" type="text" name="amount" size="14">
</div>
<a href="create.php?state=1" id="plus3" class="ui-state-default ui-corner-all" title="Add">[+]</a>
<a href="create.php?state=0" id="minus3" class="ui-state-default ui-corner-all" title="Remove">[-]</a>
here is my javascript:
$(document).ready(function(){
$("#duplicate3").dynamicForm("#plus3", "#minus3",{
limit:10,
createColor: 'yellow',
removeColor: 'red'
}
);
});
Solution
A couple of quick loops to add a number to each input could work:
$("input[name^='description']").each(function(index){
var id = "description" + (index+1);
$(this).attr("id", id);
$(this).attr("name", id);
});
$("input[name^='amount']").each(function(index){
var id = "amount" + (index+1);
$(this).attr("id", id);
$(this).attr("name", id);
});
This will get you:
<div id="duplicate3">
<input id="description1" type="text" name="description1" size="40">
<input id="amount1" type="text" name="amount1" size="14">
<input id="description2" type="text" name="description2" size="40">
<input id="amount2" type="text" name="amount2" size="14">
<input id="description3" type="text" name="description3" size="40">
<input id="amount3" type="text" name="amount3" size="14">
...
</div>
You could run the loops following the add/remove action, or you could just wait and run them before submitting the form, if you didn't need to reference the inputs for any other reason.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow