Namit
Namit

Reputation: 1322

Removing a row from a table using javascript

I am using to add a some rows using javascript. I was able to achieve that using:

$('#order_basket > tbody:last').append('<tr><td><b>'+Book+
             '</td><td>'+Type+'</td><td>'+'<span onclick="removeRow()"'+
             'class="label label-important">Remove</span></td></tr>');      
        return false;
});

Now i also want to be able to remove that row using javascript too. In the able code i have a label named as Remove which is calling another function in my javascript that is being used to remove the selected row. However i am unable to achieve that. The code i am using to remove the row is:

function removeRow() {
    $(this).parent().remove();
    return false;
}

Any help will be appreciated!

Upvotes: 0

Views: 218

Answers (1)

Rob W
Rob W

Reputation: 348972

You have to pass this inside the onclick event as follows:

'<span onclick="removeRow(this)"'

And change the function to:

function removeRow(row) {
    $(row).closest('tr').remove();
}

Instead of passing the event as an attribute via the HTML, you can also use:

        $('#order_basket > tbody:last').append('<tr><td><b>' + Book +
             '</td><td>'+Type+'</td><td>'+'<span'+
             'class="label label-important remove">Remove</span></td></tr>');      
        return false;
});

$('#order_basket > tbody:last').on('click', 'span.remove', function() {
    $(this).closest('tr').remove();
});

Upvotes: 3

Related Questions