Home > Net >  Removing data from an array when unchecking the checkbox
Removing data from an array when unchecking the checkbox

Time:08-06

For this task, I'm trying to add storyId to a favorites array when a post's checkbox is clicked. Like so: Checked Box Console result

So I've got that part working. However, when I uncheck the checkbox, the same storyId is pushed to the array: Console after unchecking

I've tried to create this using if/else statements:

async saveFavStory(storyId) {
console.log(storyId);

if (this.checked = "true") {
  this.favorites.push(storyId);
  console.log(this);
} else { 
  this.favorites.pop(storyId);
  console.log(this)
};
};

If someone could explain how to write this so that the storyId is removed from the favorites array when the checkbox is unchecked it would be much appreciated!

CodePudding user response:

When you uncheck, you need to use filter method to filter the favorites array from that specific item.

if (this.checked == true) {
  this.favorites.push(storyId);
} else { 
  this.favorites = this.favorites.filter(id => id !== storyId);
};

CodePudding user response:

You can send an attribute in the event which will tell you whether the checkbox is checked or not like this

const customEventCheck = new CustomEvent('childevent', {
detail:{val:event.target.value,checked:event.target.checked}
});

And in the parent, based on that value, you can add or remove the element.

var rowId = event.detail.val;
var checked=event.detail.checked;

if(checked){
this.checkedId.push(rowId);
}else{
    var index = this.checkedId.indexOf(rowId);
this.checkedId.splice(index, 1);
}

CodePudding user response:

Everyone will have different wants to accomplish this. I prefer to not use if statements to look through and remove unchecked items.

My solution is simple, on change regenerate the list based on what's checked.

let stories = document.querySelectorAll("[type='checkbox']");
let favorites = [];

function createFavorites() {
  favorites = [];
  let checked = document.querySelectorAll("[type='checkbox']:checked");
  checked.forEach(function(el) {
    favorites.push(el.value);
  });
  console.log(favorites)
}

stories.forEach(function(el) {
  el.addEventListener("change", function() {
    createFavorites();
  });
});
<input type="checkbox" value="1"> 1 Favorite
<input type="checkbox" value="2"> 2 Favorite
<input type="checkbox" value="3"> 3 Favorite

  • Related