user977154
user977154

Reputation: 1095

Easiest way to add a button on each row of a table HTML

I am trying to create a table in HTML that as a button on each row that acts a delete button. So when the button is click it will delete the html row as well as a row in the DB. What is the easiest way to do this?

This is what i have so far but it doesn't look good at all:

function GetSongs(id) {
    $.ajax(
    {
        type: "Get",
        url: "@Url.Action("GetSongs", "Game")",
        data: { playlistId: id },
        success: function (data) {
            json = data;
            var obj = JSON.parse(json);
            for (var i in obj) {
                songCount++;
                playlist.push(obj[i].SongURL);
                $("#song-table").append("<tr><td>" + obj[i].SongURL + "<button class=" +"editbtn" +">edit</button>"+ "</td></tr>");
            }
            $('#song-count').empty();
            $('#song-count').append('Song Count: ' + songCount);

        }
    });
}

Here is my table:

<div id="player-playlist" style="height: 300px; overflow:scroll; overflow-x: hidden">
      <table class="zebra" id="song-table" style="width:400px;">
              <tr>
                 <th>Song</th>
              </tr>
      </table>
</div>

Upvotes: 2

Views: 10229

Answers (2)

StaticVoid
StaticVoid

Reputation: 1537

Give your button an onclick Javascript function that includes the id as a parameter:

"<button type='button' onclick='deleteThisItem(" + id + ")' >delete</button>"

Javascript function:

function deleteThisItem(theID){
    // ajax call to delete theID from database
    // refresh the table
}

Upvotes: 2

Alex W
Alex W

Reputation: 38163

You can add delete buttons the same way you're adding edit buttons:

$("#song-table").append("<tr><td>" + obj[i].SongURL + "<button class=" +"delbtn" +">delete</button>"+ "</td></tr>");

$('button.delbtn').click(function(){
    $(this).parent().remove();
});

http://jsfiddle.net/qGGPZ/2/

Upvotes: 2

Related Questions