Max Lynn Max Lynn - 4 months ago 11
Javascript Question

If statement never returning true when I first hide the element

$('.checkbox').on('change', function() {
$('.pagination').hide();
$('.callout').hide();

$('.checkbox').each(function() {
if ($(this).prop('checked') === true) {
var checkboxName = $(this).val();

$('.callout').each(function() {
var calloutArray = $(this).data();
var i;
for (i = 0; i < calloutArray.category.length; i++) {
$(this).hide();

if (checkboxName === calloutArray.category[i]) {
$(this).show();
}
}

});
}
});
});


To explain this function it basically listens to see if a checkbox has been clicked and then hides all the callouts on the page.

It then loops through each one of those checkboxes and checks which ones are true on the page. I then create a variable that stores the current checkbox value.

After this I then want to loop through each callout and pull its data from a data attribute.

I then loop through each string in the array and hide the callout no matter what. However if the callout has an array value that is the same as the checkbox value then I need to show it.

This seems to be working without the hide. However I need to hide the callouts if they do not hold the same checked category names which is where I'm running into problems.

The If statement seems to never return true if I have already hidden the callout. So the question is how do I show the callout if the selected checkboxes match one of the callout array strings but hide the callout if the string is not in the callout array.

Answer

From what I've understand, the following code is equivalent

$('.checkbox').on('change', function () {
    $('.pagination, .callout').hide();

    $('.checkbox:checked').each(function () {
        var checkboxName = $(this).val();

        $('.callout').hide().each(function () {
            var calloutArray = $(this).data();

            if (calloutArray.category.indexOf(checkboxName) !== -1) {
                $(this).show();
            }
        });
    });
});
  1. Merge selectors having common actions(hide())
  2. Use :checked pseudo-selector to select only checked elements
  3. Use hide() on selector and then iterate over it using each()
  4. Use indexOf to check if element is in array