Redwall
Redwall

Reputation: 1020

Add / Delete Rows from Table

I have created a table in Twitter Bootstrap here

I want to be able to do 2 things with it

  1. Delete rows by pressing delete icon - will delete that row

  2. Add a new name by adding text (name) to input field and then pressing "add new row"

DEMO - http://jsfiddle.net/qxdz4/2/

Looking for a way to do this with JavaScript / jQuery

My Code

<div class="input-prepend input-append"><span class="add-on"><i class="icon-picture"></i></span>

<input class="span2"
id="appendedInputButton" type="text" placeholder="Add New Name Here">
<button class="btn" type="button">Add New Row</button>
</div>
<table id="users" class="table table-bordered table-condensed">
<tr>
    <th>name</th>
    <th></th>
</tr>
<tr>
    <td><a href="#" data-pk="1">Mike</a>

    </td>
    <td class="taskOptions"> <a href="#deleteProject" rel="tooltip" data-toggle="modal" class="tip-top"
        data-original-title="Delete Row"><i class="icon-remove"></i></a>

    </td>
</tr>
<tr>
    <td><a href="#" data-pk="2">John</a>

    </td>
    <td class="taskOptions"> <a href="#deleteProject" rel="tooltip" data-toggle="modal" class="tip-top"
        data-original-title="Delete Row"><i class="icon-remove"></i></a>

    </td>
</tr>
<tr>
    <td><a href="#" data-pk="3">Mary</a>

    </td>
    <td class="taskOptions"> <a href="#deleteProject" rel="tooltip" data-toggle="modal" class="tip-top"
        data-original-title="Delete Row"><i class="icon-remove"></i></a>

    </td>
</tr>
</table>

Notes

Upvotes: 0

Views: 10886

Answers (6)

user1922106
user1922106

Reputation:

I would suggest you yo use following jQuery functions:

on(), click(), remove(), append()

Please do research on this, also look at the jQuery selectors in order to find how to select proper row.

Upvotes: 0

Duk
Duk

Reputation: 927

First you create one method AddmultipleInput()

Inside the function,

    .AddMultipleInput = function (btnAddId, btnDelId, inputContainerIdPrefix, inputContainerCss, firstChildInputIdPrefix) {
    if ($('.' + inputContainerCss).length < 2) {
        $('#' + btnDelId).attr('disabled', 'disabled');
    }

    $('#' + btnAddId).click(function () {
        var num = $('.' + inputContainerCss).length; // how many "duplicatable" input fields we currently have
        var newNum = new Number(num + 1);   // the numeric ID of the new input field being added

        // create the new element via clone(), and manipulate it's ID using newNum value
        var newElem = $('#' + inputContainerIdPrefix + num).clone().attr('id', inputContainerIdPrefix + newNum);
        
        newElem.children().each(function () {
            var idPrefix = $(this).attr('id').substring(0, $(this).attr('id').length - 1);
            var namePrefix = $(this).attr('name').substring(0, $(this).attr('name').length - 1);
            $(this).attr('id', idPrefix + newNum).attr('name', namePrefix + newNum);
        })

        // insert the new element after the last "duplicatable" input field
        $('#' + inputContainerIdPrefix + num).after(newElem);

        // enable the "remove" button
         $('#' + btnDelId).attr('disabled', '');

        // business rule: you can only add 5 names
        if (newNum == 5)
            $('#' + btnAddId).attr('disabled', 'disabled');

});

    $('#' + btnDelId).click(function () {
        var num = $('.' + inputContainerCss).length;

        $('#' + inputContainerIdPrefix + num).remove();
        $('#' + btnAddId).attr('disabled', '');
        if (num == 2)
            $('#' + btnDelId).attr('disabled', 'disabled');
    });

Upvotes: 1

BenM
BenM

Reputation: 53198

You can easily remove the row by doing this:

$('td.taskOptions a.tip-top').on('click', function(e) {  
    e.preventDefault();
    $(this).tooltip('hide');
    $(this).parents('tr').remove();
});

Similarly, adding a new row can be done as follows:

$('button.btn').click(function(e) {  

    e.preventDefault();
    var the_name = $.trim($('#appendedInputButton').val());

    var new_row = $('<tr>\
                         <td>\
                             <a href="#" data-pk="1">'+the_name+'</a>\
                         </td>\
                         <td class="taskOptions">\
                             <a href="#deleteProject" rel="tooltip" data-toggle="modal" class="tip-top" data-original-title="Delete Row"><i class="icon-remove"></i></a>\
                         </td>\
                      </tr>');
    new_row.appendTo($('#users'));
});

Please note that it might be worth adding a more specific class name to the button (when clicked to add the row) to avoid any confusion. An ID would work just as well.

I've updated your jsFiddle with the additional functionality. You can see here.

Upvotes: 4

cernunnos
cernunnos

Reputation: 2806

Add a class to your delete links (like delete-row) and use something like:

$(document).on("click",".delete-row",function(ev) {
    ev.preventDefault();
    $(this).tooltip('hide');
    $(this).parents("tr").first().remove();
});

Note: "$(this).tooltip('destroy');" would be better than "hide", but your fiddle bootstrap version doesn't support destroy yet. Also, you can set $("#users") instead of $(document) as handler for this event if you want, so long as the delete-row buttons are children of the handler the event gets delegated properly.

To add a line the answer of BenM should work perfect.

PS:

.parents(selector) function travels more than one level up the DOM tree, while .parent() travels a single level up the DOM tree.

.parents(selector) function selects all parents that match the selector, so in case there is a change you end up putting a table inside a table (accidentally im sure) you should use .first(), ensuring you dont remove the wrong row.

Edit: As mentioned by BenM, the previous code would not work with new lines, forgot the add part of the question, the new code should work.

Upvotes: 0

Suraj Shrestha
Suraj Shrestha

Reputation: 1808

$('.icon-remove').live('click',function(){
    $(this).parent('tr').remove();
});

If you are using jQuery 1.7 or above, then use .on instead of .live.

Upvotes: 0

Keeper Hood
Keeper Hood

Reputation: 594

I don't know how you obtain each row's pk data (data-pk) attribute. That's up to you On document.Ready

$('[rel=tooltip]').tooltip();
function bindCloseButtons(){
    $("#users td.taskOptions a").click(function(e){
        $(this).parent().parent().remove();
    });
}

function addTableRow(name , pk){

    // name column
    var row = $("<tr></tr>");
    row.append('<td><a href="#" data-pk="'+pk+'">'+name+'</a></td>');

    // close button
    var btnClose = $('<td class="taskOptions"> <a href="#deleteProject" rel="tooltip" data-toggle="modal" class="tip-top" data-original-title="Delete Row"><i class="icon-remove"></i></a></td>');

    row.append(btnClose);

    $("#users").append(row);
    bindCloseButtons();
    $('[rel=tooltip]').tooltip();
}

$("#addNew").click(function(e){
    var name = $("#appendedInputButton").val();
    var pk = 1; // TODO: set your pk here 
    addTableRow(name, pk);

});

bindCloseButtons();

Here's a fiddle: http://jsfiddle.net/qxdz4/16/

Upvotes: 2

Related Questions