0

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!

0

3 Answers 3

1

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);
};

Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

Comments

0

Everyone will have different ways 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.