Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  197] [ 7]  / answers: 1 / hits: 86658  / 12 Years ago, thu, june 14, 2012, 12:00:00

I am new to HTML and JavaScript. I got a problem like this in HTML (This code below only visualize the problem for you to easy to reference.)



<tr>
<td>1</td>
<td>Harry</td>
</tr>
<tr>
<td>2</td>
<td>Simon</td>
</tr>
<td>3</td>
<td>Maria</td>
</tr>
</tr>
<td>4</td>
<td>Victory</td>
</tr>


This is a name list, however the problem is that sometime i need to add more name into this table and I HAVE TO ADD in front of Number 1, so meaning i have to re-write the number list, (EX: 1 1 2 3 4 --> 1 2 3 4 5). I feel that is not a good way.



NOTE: I don't want to change the list number decrease from top to bottom. And this is a HTML file so can't apply PHP



Anyone can help me to make the number to a variable like i and a function can help me to fill variable i increment from top to bottom automatically like



<tr>
<td>i</td>
<td>Harry</td>
</tr>
<tr>
<td>i</td>
<td>Simon</td>
</tr>
<td>i</td>
<td>Maria</td>
</tr>
</tr>
<td>i</td>
<td>Victory</td>
</tr>


Function Fill_i for example:
I think that JavaScript should be used in this case. Thanks for your help and suggestion on this problem.



Again: I am not allowed to use PHP or ASP and when I add a new name, I add it manually by HTML.


More From » html

 Answers
38

This should work for you:



<table>
<tr>
<td>Harry</td>
</tr>
<tr>
<td>Simon</td>
</tr>
<tr>
<td>Maria</td>
</tr>
<tr>
<td>Victory</td>
</tr>
</table>
<script>
var tables = document.getElementsByTagName('table');
var table = tables[tables.length - 1];
var rows = table.rows;
for(var i = 0, td; i < rows.length; i++){
td = document.createElement('td');
td.appendChild(document.createTextNode(i + 1));
rows[i].insertBefore(td, rows[i].firstChild);
}
</script>


The script should be placed immediately after your table. It goes through each row of your table and adds an extra cell to the beginning with the incrementing number inside that cell.



JSFiddle Demo


[#84920] Wednesday, June 13, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mariann

Total Points: 201
Total Questions: 133
Total Answers: 107

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;