0

I have an array with HTML Elements and I would like to addclass to the elements where his data-id is equal to ids in a array retrieve after an ajax called. I explain, I have this :

function update_b() {
  var $bookIds = $(".js-book").map(function() {
    return $(this).data("id");
  }).get();

  $.ajax({
    type: 'GET',
    url: ajaxurl,
    data: {
      action: 'verify_books',
      books: $bookIds
    },
    success: function(data){
      if(data) {
     // if ID in data is the same as data-id in the $books
     //   $books.addClass('is-active');
      }
    },
  });

And I have this in PHP to verify if the boosk are in my data

function verify_boos(){

  $books = $_GET['books'];

  $userId = get_current_user_id();
  $library = get_user_meta($userId, 'library', true);

  return array_intersect($books, $favoris);

}

When I log data in my success function I have for example an array with two Ids of books. I want to addClass on these two buttons who have the same id in "data-id". How can I do this ?

Andreas
  • 21,535
  • 7
  • 47
  • 56
chtouk
  • 303
  • 4
  • 13
  • What have you tried so far to solve this on your own? – Andreas Oct 10 '22 at 08:30
  • Not an answer to your question, but I just want to point out that [you might not need jQuery](https://youmightnotneedjquery.com/). – Lorik Oct 10 '22 at 08:32
  • @Andreas I tried to loop in by book sbtn and in my data but I don't know how to combine both – chtouk Oct 10 '22 at 08:33
  • Is there a reason you can't do a loop? Which part are you stuck on? The loop? `$(".js-book").each(` reading data `$(this).data("id")`? array contains/includes? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes – freedomn-m Oct 10 '22 at 08:34
  • 1
    Thank you! It was not "how to selected a data attribute" missing but the missing brick for me was the term "includes" ! – chtouk Oct 10 '22 at 08:42

1 Answers1

0

Assuming that the server (your PHP snippet) returns an array of book ids, you can use this to make it work:

function update_b() {
  var $bookIds = $(".js-book").map(function() {
    return $(this).data("id");
  }).get();
  $.ajax({
    type: 'GET',
    url: ajaxurl,
    data: {
      action: 'verify_books',
      books: $bookIds
    },
    success: function(data){
      if(data) {
        $(".js-book").each(function(index, element) {
           if (!data.includes($(this).data("id")) return;
           $(this).addClass("is-active");
        });
      }
    },
  });

So we iterate through all elements with the class "js-book" and check, wether the value of the data-id attribute is included in the array returned by the server. If it is, than add the desired class to the element.

Fatorice
  • 515
  • 3
  • 12