lundi 27 novembre 2017

Add/remove checkbox values to/from array when checked and unchecked (jQuery)

On a project I'm currently working on, I'm using radio buttons and AJAX to change the posts displayed on a custom WordPress template page. It works perfectly, however, the client would like it to be checkboxes instead of radio inputs so that each time a user selected a new category, it adds to the posts being displayed instead of replacing it.

For example: currently, if you click category1, category1 posts show up. Click category2, and category2 posts replace the category1 posts. The client would like BOTH category1 and category2 to show up if both checkboxes are selected.

Here's my JS currently:

jQuery(document).ready(function ($) {
  // AJAX Post Filter scripts
  var $checkbox = $("#filter input:checkbox");
  var $checked = $("#filter input:checkbox:checked");
  var $unchecked = $("#filter input:checkbox:not(:checked)");
  $checkbox.change(function () {
    if ($checked) {
      var catID = $(this).val();

      $.ajax({
        type: 'POST',
        url: afp_vars.afp_ajax_url,
        data: {
          "action": "load-filter",
          category__in: catID
        },
        success: function (response) {
          $(".filter-section").empty().html(response);
          return false;
          console.log('success!');
        }
      });
      console.log(catID);
    }
  });
});

I'm pretty sure I need to do something with .map() with my variable catID as I've seen in some other threads, but I haven't been able to find a solution that works quite right for me.




Aucun commentaire:

Enregistrer un commentaire