mercredi 30 août 2017

Why is this nested JavaScript function running twice?

I've got a long input:selectbox list. The list is essentially a filter that shows/hides information on the page based on what's selected/not selected.

In the list, if something is checked I want the corresponding <div> to show. If something is unchecked I want the corresponding <div> to hide.

Simple enough? Apparently not for me. :(

Code:

$('.ddFilter input:checkbox').off().on('click', function() {

  $('.hideFrequent').slideUp();

  $('input:checkbox:not(:checked)').each(function() {
      $('div.' + $(this).val()).slideUp();
  });

  $('input:checkbox:checked').each(function() {
      $('div.' + $(this).val()).slideDown();
  });
});

The first nested function, $('input:checkbox:not(:checked)'), always runs twice. The first time it runs it hides everything that is not checked. The second time it runs it hides everything.

If that function comes after the :checked function, then no matter how you interact with the list, everything is always hidden. If I put that function first, everything that is unchecked is hidden, then all things are hidden, then the :checked function runs and re-displays the <divs> associated with the checked checkboxes.

What'm I doing wrong?




Aucun commentaire:

Enregistrer un commentaire