Lars Holmqvist
Lars Holmqvist

Reputation: 81

Dynamic HTML row - add id on TR

How to add an ID (value 1, 2, 3, etc.) on each new I have now so that my script creates a new row, but would need an ID to each

FIDDLE

CODE:

function deleteRow(tableID) {
    try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        for(var i=0; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked) {
                if(rowCount <= 1) {
                    alert("Cant delete all rows");
                    break;
                }
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
    }catch(e) {
        alert(e);
    }
}

Upvotes: 1

Views: 11574

Answers (2)

You can use jQuery to make it easier:

<head>
    <script src="js/jquery-1.11.1.min.js"></script>
</head>
<body>
   <script>
   $("#create_button").click(function(){
      $("<tr>").attr({"id":"id_"+number}).appendTo("#table");
   ]);
   </script>
   ...
   ...
</body>

Upvotes: 0

pavel
pavel

Reputation: 27082

So, simply add id when you create new line. Removed IDs aren't used again, ID is still unique.

var row_id = 1;

function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.id = 'id' + row_id; // ID is 'id#' because valid ID can't start with a number
    row_id++;
    ...

http://jsfiddle.net/pkz1vszu/2/

Upvotes: 4

Related Questions