The Javascript increments each visible number in these dynamically generated rows of a static table.
The jQuery dutifully hides each row when clicked, but, of course, the numbers don’t change. How can I use jQuery to re-number the rows when the visitor is done removing the unwanted lines? I want the user to click ‘renumber’ to renumber the remaining rows correctly. What I have didn’t work 🙂
Help is deeply appreciated.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var keepTrack = 1;
</script>
<table>
<tr><td colspan="2" id="renumber">renumber</td></tr>
<tr id="sWH1">
<td>
<script>
document.write(keepTrack);keepTrack++;
</script></td>
<td>someWordsHere</td></tr>
<script>
$(document).ready(function() {
$("#sWH1").click(function() {
$("#sWH1").hide(100);});
});</script>
<tr id="sWH2">
<td>
<script>
document.write(keepTrack);keepTrack++;
</script></td>
<td>someWordsHere</td></tr>
<script>
$(document).ready(function() {
$("#sWH2").click(function() {
$("#sWH2").hide(100);});
});</script>
<tr id="sWH3">
<td>
<script>
document.write(keepTrack);keepTrack++;
</script></td>
<td>someWordsHere</td></tr>
<script>
$(document).ready(function() {
$("#sWH3").click(function() {
$("#sWH3").hide(100);});
});</script>
</table>
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function() {
$("#renumber").click(function() {
'magically renumber the remaining table rows'
});
});
</script>
The straightforward answer
To renumber the rows you can use the
each()method that allows you to iterate over a set of elements (the rows in this case) and provides anienumerator parameter.A general example:
Now to do this, you’ll need to define better selectors. The problem with your current code is that your selectors are too specific. This prevents you from creating general event handlers, instead of creating a click handler for each row.
How to improve your code
Consider setting a class for the relevant numbered rows. This will allow you to create a single click handler for all rows and make the relevant rows much easier to select when renumbering.
For example:
HTML
Javascript
Note how by adding two classes
numbered_rowandrow_numberwe are able to do everything efficiently in one block of code: initial numbering of the rows, a single click handler to hide them and the renumbering action.An even more general approach
If you wanted, you could make this even more general and efficient, by chaining the
each()andon()methods as well as handling the renumbering within theon()each time a row is hidden.For example: