I have a form, i have dynamically added inputs, i have change index of each input when it is added dynamically.
Here is my html form.
$(function(){
var hobiesIndex = 1;
$("#add_field").click(function () {
$(this).closest('tr').find('input.hobies').attr('name', "hobies['"+hobiesIndex+"']");
$("#table_container").append($("#temp_div").html());
hobiesIndex++;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" method="POST" enctype="multipart/form-data">
<table id="table_container">
<tr>
<th><label class="lbl-header">My Hobies</label></th>
<th><label class="lbl-header">Image</label></th>
</tr>
<tr>
<td><input type="text" class="hobies" name="hobies[0]" value=""></td>
<td>
<input id="file-input" class="imgInp" type="file" name="image[0]" />
</td>
</tr>
</table>
<p class="contact">
<a class="button" id="add_field"><span style="text-transform: uppercase;"> + Add More</span></a>
</p>
<input type="submit" name="submit" value="Submit">
</form>
<table class="product_sku_input" id="temp_div" style="display: none">
<tr>
<td><input type="text" class="hobies" name="hobies[]" /></td>
<td>
<input id="file-input" class="imgInp" type="file" name="image[]" />
</td>
</tr>
</table>
Here is my script code.
</div>
Target the last input
in each click:
Change
$(this).closest('tr').find('input.hobies').attr('name', "hobies['"+hobiesIndex+"']");
To
$('input.hobies').last().attr('name', "hobies["+hobiesIndex+"]");