1

I am trying to renumber rows in my table using jQuery

This is the generated HTML

...
...
<tr>
<td><input type="hidden" class="counter" value="5"></td>
<td><input type="text" size="40" id="drugName5" name="drugName[5]" class="drugName required" value=""></td>

<td><input type="text" name="dose[5]" class="dose" value=""></td>
<td><input type="text" name="days[5]" class="days" value=""></td>
<td><input type="image" src="images/delete.png" class="removeRow"></td>
</tr>
 ....
....

Now clicking the delete.png triggers this function

$(function(){
  $("#right").delegate(".removeRow", "click", function(){
          var counter = $(this).parent("td").parent("tr").find(".counter").val();
          $(this).parent("td").parent("tr").remove();

          $(this).parent("td").parent("tr").parent().find("tr").each(function() {
                 var curIndex = $(this).find(".counter").val();
                 if (curIndex  > counter) {
                       $(this).find(".counter").attr("value", "" + (curIndex - 1) + ""
                       //Change Other Numbers Here
                      //......

);
  }
});

Why isn't this working?

Am I navigating the DOM the wrong way?

Or is it a problem the way I am trying to renumber?

Please help/give references.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mr Hyde
  • 3,393
  • 8
  • 36
  • 48

1 Answers1

1
$(this).parent("td").parent("tr").remove();

      $(this).parent("td").parent("tr").parent().find("tr").each(...

try not to remove an element that You refer to in the future. Put remove at the end of the function.

On the other hand I'd do something like this (assuming that numbers are consistent):

$tr=$(this).parent('tr');
$tb=$tr.parent('table');
$tr.remove();
$tb.find('tr').each(function(c){
 $(this).find('td:first input').val(c);
 });

And finally - I always use id attribute in tr for numbers of rows etc.

naugtur
  • 16,827
  • 5
  • 70
  • 113
  • Hey It Worked. You are geniuses! – Mr Hyde Sep 29 '10 at 10:40
  • It took a while, but now i see what you are getting at. – Mr Hyde Sep 29 '10 at 11:42
  • I'm just suggesting You should not count the numbers from existing ones, but just generate them from html structure if possible. And it will be faster than Your current idea, because You do a lot of traversing at the moment. – naugtur Sep 30 '10 at 11:07