nagazi nagazi - 3 months ago 9
jQuery Question

Assign object to var in each

I have a very simple jQ function, but I cannot assign the "row" to the "tablerow" var.

I dont know why :(

$(document).on('click', '.btn-remove-entry', function() {
var tablerow = null;
$.each($('.filter'), function(idx, row) {
if($(row).hasClass('info')) {
talberow = $(row);
console.log(talberow);
}
});
console.log(tablerow);
if(tablerow != null) {
$('.filter-list tr').remove(tablerow);
}
});


The Tablerow is at every time 'null'. The first console shows me the correct table row. But the Second at line 9 logs 'null' again.

Why?




The working result

$(document).on('click', '.btn-remove-entry', function() {
$.each($('.filter'), function(idx, row) {
if($(row).hasClass('info')) {
$(row).remove();
}
});
});

Answer

It is tablerow not talberow. And you can use the each with the selector directly.

$(document).on('click', '.btn-remove-entry', function() {
    var tablerow = null;

    $('.filter').each(function() {
        if($(this).hasClass('info')) {
            tablerow = $(this);
        }
    });

    if(tablerow != null) {
        $('.filter-list tr').remove(tablerow);      
    }
});
Comments