-1

This my code:

jQuery(document).on('click', '.list li', function(e){
    var container = $('#button');
    var selectedList = container.attr('data-selected-list');

    if(jQuery(this).hasClass('done')){
        jQuery(this).removeClass('done');

        var myElement = jQuery(this).attr('data-user-id');
        var myArray = selectedList;

        for (var i = myArray.length - 1; i >= 0; i--) {
          if (myArray[i] == myElement) myArray.splice(i, 1);
        }
        container.attr('data-selected-list', myArray);
    } else {
        jQuery(this).addClass('done');

        if (!selectedList) {
          selectedList = [];
        } else {
          selectedList = JSON.parse(selectedList);
        }

        selectedList.push(jQuery(this).attr('data-user-id'));
        selectedList = JSON.stringify(selectedList);

        container.attr('data-selected-list', selectedList);
    }
});

I successfully make when user click on .list li get the user id and add it as array into data-selected-list.

My question is how can make when unclick remove the user-id from data-selected-list (the array list)?

I search on stackoverflow but i failed to make this.

John Dors
  • 9
  • 2

1 Answers1

0

You need to use JSON.parse() and JSON.stringify() when removing from the array, just like you do when you add to it.

if(jQuery(this).hasClass('done')){
    jQuery(this).removeClass('done');

    var myElement = jQuery(this).attr('data-user-id');
    var myArray = selectedList ? JSON.parse(selectedList) : [];

    for (var i = myArray.length - 1; i >= 0; i--) {
      if (myArray[i] == myElement) myArray.splice(i, 1);
    }
    container.attr('data-selected-list', JSON.stringify(myArray));
} 

Another option would be to use .data() instead of .attr(). This stores the information internally in jQuery, and it can store any type.

Barmar
  • 596,455
  • 48
  • 393
  • 495