Rafael Spessotto
Rafael Spessotto

Reputation: 161

JQuery Add a Button in a Table Row

I want to add a button who will edit the row in the table. My code is:

$("#tabprincipal tbody").html("");
    $.getJSON("carrega_usuarios.php?vPagina=" + 0+ "&vQtdeLinhas=" + 10,function(data){
    $.each(data.users, function(i,user){
    var newRow =
    "<tr>"
    +"<td>"+user.ID+"</td>"
    +"<td>"+user.USER+"</td>"
    +"<td>"+user.GROUP+"</td>"
    +"<td>"+user.NUMBER+"</td>"
    +"<td>"+user.STATE+"</td>"
    +"<td>"+user.BIRTH+"</td>"
    +"<td> <button id='but1' class='botaoadd'>hello </button> </td>"
    +"</tr>" ;
    $(newRow).appendTo("#tabprincipal tbody");
    });
    });

But the button doesn't appear in the table cell.

Upvotes: 0

Views: 14313

Answers (1)

davcs86
davcs86

Reputation: 3935

A very basic example of how make dynamic tables with jQuery

HTML

<table id="tabprincipal">
    <tbody></tbody>
</table>

<button id="addRow">Add row</button>

CSS

.tabrow td div { width: 100%; }

.tabrow.editing td div:first-of-type, 
.tabrow.closed td div:last-of-type  {
    display:none;
}

.tabrow.editing td div:last-of-type, 
.tabrow.closed td div:first-of-type  {
    display:block;
}

JAVASCRIPT

jQuery(function(){
    $("body").on("click","#addRow",function(ev){
        var len = $("#tabprincipal tbody tr").toArray().length;
        var newRow = "<tr class='tabrow closed'>"
        +"<td><div>"+len+"</div><div><input type='text' value='"+len+"'/></div></td>"
        +"<td><div>A"+len+"</div><div><input type='text' value='A"+len+"'/></div></td>"
        +"<td><div><button class='editRow'>Edit row</button></div><div><button class='saveRow'>Save row</button></div></td>"
        +"</tr>";
        $(newRow).appendTo("#tabprincipal tbody");
    });

    $("body").on("click",".editRow",function(ev){
       $(this).parents(".tabrow").removeClass("closed").addClass("editing");
    });

    $("body").on("click",".saveRow",function(ev){
        var row = $(this).parents(".tabrow");
        // update the cells
        row.find("td").each(function(){
           // new value
           var newVal = $(this).find("input").val();
           $(this).find("div:first").html(newVal);
        });
        row.removeClass("editing").addClass("closed");
    });
});

See it on action here

Upvotes: 2

Related Questions