Reputation: 9466
I've got a form inside of a table, something like this:
<form action="" method="post">
<table>
<tbody class="rowAdder">
<tr>
<td><input name='info[5]' /></td>
<td><input name='other_info[5] /></td>
</tr>
</tbody>
</table>
</form>
I want to clone the 'tr' element and in the clone I want to increment the index values.
PHP natively treats input names with "[]" as arrays. But I haven't found any way to easily play with that index value in jQuery.
I know I can use ("input[name$=']']")
to find all elements on the page with names ending in ']' but that doesn't help me. I won't always know what the "name" element will look like, so using a cumbersome string index method won't work alone. Although, perhaps an even more cumbersome method will.
I just want to find the names that are arrays and increment them when adding a row. I hope there is a simple, elegant way to do it.
var $array_inputs = clone.find("input[name$=']']");
That works to get the correct elements, although it is clunky. Now I need to increment 5's to 6's
Upvotes: 1
Views: 1180
Reputation: 41885
I don't know which is the best way but clearly, it can be done using a bit of this:
<form action="" method="post">
<table>
<tbody>
<tr>
<td><input name='info[5]' /></td>
<td><input name='other_info[5]' /></td>
</tr>
</tbody>
</table>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var last_child = $('table tbody tr:last-child'); // point the last row
var children_input = last_child.children('td:eq(0)').children('input'); // get the input tag
var index_num = children_input.attr('name'); // get its attr name
var get_index = index_num.split('[').pop().split(']').shift(); // extract the index
alert(get_index);
});
</script>
Upvotes: 1