Search code examples
javascriptjqueryattr

Set the id of a dynamically created tr tag


I have a table and rows that are being created dynamically into that table as seen below:

 $("body").on("click","#addRow",function(ev){
    
    var newRow = "<tr class='tabrow editing'>"
        +"<th><div></div><div><input type='text' class='form-control' value=''/></div></th>"
        // +"<td><div>A"+len+"</div><div><input type='text' value='A"+len+"'/></div></td>"
        +"<th><div><button class='editRow ' type='button'>Edit</button></div><div><button class='deleteRow ' type='button'>Delete</button></div><div><button class='saveRow' type='button'>Save</button></div></th>"
        +"</tr>";

    
    $(newRow).appendTo("#data_table tbody");

});

How do I add an id just for the at the beginning?

I have tried

        $(newRow).find('tr').attr('id' , 'row' + someNumber);

Solution

  • You can add id like this

    $("body").on("click","#addRow",function(ev){
    
    var newRow = "<tr class='tabrow editing' id='row"+someNumber+"'>"
        +"<th><div></div><div><input type='text' class='form-control' value=''/></div></th>"
        // +"<td><div>A"+len+"</div><div><input type='text' value='A"+len+"'/></div></td>"
        +"<th><div><button class='editRow ' type='button'>Edit</button></div><div><button class='deleteRow ' type='button'>Delete</button></div><div><button class='saveRow' type='button'>Save</button></div></th>"
        +"</tr>";
    
    
    $(newRow).appendTo("#data_table tbody");
    
    });
    

    or like this (as in @Lain's comment)

    $("body").on("click","#addRow",function(ev){
    
    var newRow = "<tr class='tabrow editing'>"
        +"<th><div></div><div><input type='text' class='form-control' value=''/></div></th>"
        // +"<td><div>A"+len+"</div><div><input type='text' value='A"+len+"'/></div></td>"
        +"<th><div><button class='editRow ' type='button'>Edit</button></div><div><button class='deleteRow ' type='button'>Delete</button></div><div><button class='saveRow' type='button'>Save</button></div></th>"
        +"</tr>";
    
    $(newRow).attr('id' , 'row' + someNumber);
    $(newRow).appendTo("#data_table tbody");
    
    });