Aleks Kpur Aleks Kpur - 5 months ago 11
jQuery Question

Javascript - Getting removed item name from table?

So I have an table. By click of a button, information will be added there, so each item has also X button, which removes them from the list. I've been trying to do that, if you click that X button, then it will output to console the item name which you deleted. How could I do that?

Here's the function

function sitaSeen(img, name, condition, price) {
$('tbody').append("<tr id='itemCart'><td><img src=" + img + "></td><td>" + name + "</td><td>" + condition + "</td><td>$" + price + "</td><td><span>X</span></td></tr>");


Which is called, when item has to be added.

Here's the X button code

$(document).ready(function() {
$('.sweet-container').on('click', 'tr span', function(){
var removedname = $(this).closest('tr').ignore('span').text();
console.log(removedname);
$(this).closest('tr').remove();
});
});


There's also kind of my try, but ofc it wont work.

Answer

There is no ignore() method in jQuery so it will throws error in console. So either clone the tr and remove span from cloned object and then get text or get all td which is not contains span and get text.

$(document).ready(function() {
    $('.sweet-container').on('click', 'tr span', function(){
        var removedname = $(this).closest('tr').clone().remove('span').text();
        // or
        // var removedname = $(this).closest('tr').find('td:not(:has(span))').text();
        console.log(removedname);
        $(this).closest('tr').remove();
    });
});

UPDATE : Since you just want the second column you can use :nth-child or :eq() selector

$(document).ready(function() {
    $('.sweet-container').on('click', 'tr span', function(){
        var removedname = $(this).closest('tr').find('td:nth-child(2)').text();
        // or
        // $(this).closest('tr').find('td:eq(1)').text();
        // or
        // $(this).closest('tr').children().eq(1).text();
        console.log(removedname);
        $(this).closest('tr').remove();
    });
});
Comments