Descendents of a table row
I have a table with several rows containing several cells of form inputs (see HTML snippet below). I have a function that removes and individual rows and I'm trying to reindex all of those that remain by iterating over each row (to get the new row index) and, within that, iterating over each input ($('td input', $row).each( ... )
) and updating the name
and id
attributes. What I'm finding is that the inputs in the first cell get reindexed, but not the cost input in the second cell.
Any idea what I'm missing that's keeping that second cell from get开发者_StackOverflow中文版ting updated?
Thanks.
HTML Snippet:
<tbody>
<tr>
<td>
<input type="hidden" name="data[Ticket][0][id]" value="" id="Ticket0Id">
<input type="hidden" name="data[Ticket][0][date_id]" value="" id="Ticket0DateId">
<input name="data[Ticket][0][name]" type="text" maxlength="45" value="" id="Ticket0Name">
</td>
<td>
<input name="data[Ticket][0][cost]" type="text" value="" id="Ticket0Cost">
</td>
</tr>
<tr>
<td>
<input type="hidden" name="data[Ticket][1][id]" value="" id="Ticket1Id">
<input type="hidden" name="data[Ticket][1][date_id]" value="" id="Ticket1DateId">
<input name="data[Ticket][1][name]" type="text" maxlength="45" value="" id="Ticket1Name">
</td>
<td>
<input name="data[Ticket][1][cost]" type="text" value="" id="Ticket1Cost">
</td>
</tr>
</tbody>
By popular demand, here's the jQuery snippet that attempts to do the reindexing:
// $tbody references the <tbody> element in the snippet above
$('tr', $tbody).each( function( i, row ) {
var $row = $(row);
$('td input', $row).each( function( j, input ) {
$(input).attr( 'id', $(this).attr( 'id' ).replace( /\d+/g, i ) )
$(input).attr( 'name', $(this).attr( 'name' ).replace( /\d+/g, i ) );
})
});
Use this instead as your selector:
$tr.find('input').each(function(j, input) { });
It looks like I may have been relying too heavily on Safari's web inspector to determine whether the attributes were being reindexed. It seems that if you have an element expanded, changes to that element are not reflected when they happen. Next time, I'll verify with jsfiddle first (or at least second). Lesson learned.
This one's on me. Sorry, folks.
精彩评论