简体   繁体   中英

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.

edit: I realized I needed to clarify what I have tried.

I've used the following code:

var catID = $(this).map(function () {
  return $(this).val();
}).get();

But all it does is replace the variable value with the new checkbox value. I need to add to the value without erasing the already checked values. Then if a checkbox is unchecked, I need to remove the value from the array.

I would try something like this:

let categoryIDs = [];

$('.checkbox').click((e) => {
  let id = e.currentTarget.id

  $(selector).html('')
  categoryIDs.indexOf(id) === - 1 ? (
    categoryIDs.push(Number(id))
  ) : (
    categoryIDs = categoryIDs.filter((item) => item !== id )
  )

  console.log(categoryIDs)
  categoryIDs.forEach((item) => {
    //ajax calls here

    //$.ajax({blah blah}).done(res => {
      //$(selector).append(res)
      //})
    console.log(item);
  })
})

See it in action here:

https://jsfiddle.net/mwypd9ve/

This way the IDs you want to display are always in the array, and every time the array changes the page will reflect only the content matching the IDs in the array (because you clear the section .html('') then in the loop append each ajax response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM