Scott Scott - 6 months ago 18
Javascript Question

Default option for javascript/jQuery filter hides all table rows

Please take a look at the following jsfiddle.

https://jsfiddle.net/51Le6o06/42/

As you can see the table filter ('.filter-gift') populates itself with data from the HTML table below it. I have hidden all other scripts to make this easier to see.

The problem is when I select a filter for instance "Free TV" the corresponding table filters correctly, but if I then select the default filter option in the table the filter hides all rows.

Ideally selecting the default option "-Select-" should display all rows, how can I change my code so this is the case with my function.

jQuery/Javascript used:

$(document).ready(function() {
$('.filter-gift').each(filterItems);
});

function filterItems(e) {
var items = [];
var table = '';
tableId = $(this).parent().parent().attr('tag')

var listItems = "";
listItems += "<option value='0'> -Select- </option>";
$('div[tag="' + tableId + '"] table.internalActivities .information').each(function (i) {
var itm = $(this)[0].innerText;
if ($.inArray(itm, items) == -1) {
items.push($(this)[0].innerText);
listItems += "<option value='" + i + "'>" + $(this)[0].innerText + "</option>";
}
});

$('div[tag="' + tableId+ '"] .filter-gift').html(listItems);

$('.filter-gift').change(function () {
var tableIdC = $(this).parent().parent().attr('tag');

var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
$('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
$(this).show();
$(this).prev().show();
$(this).next().show();
}
else {
$(this).hide();
$(this).prev().hide();
$(this).next().hide();
}
});
});
}

Answer

set value to 999 > use if($(this).val()!= 999) else statement as below

$('.filter-gift').change(function () {
    if($(this).val()!= 999) {
        var tableIdC = $(this).parent().parent().attr('tag');

        var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
            $('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
                if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
                    $(this).show();
                    $(this).prev().show();
                    $(this).next().show();
                }
                else {
                    $(this).hide();
                    $(this).prev().hide();
                    $(this).next().hide();
                }
            }); 
            } else {
            $(this).parent().parent().find('table tr').show();
            }
        }); 
Comments