Reputation: 37
I am trying to add an element when a checkbox is check and remove that same element when a user unchecks the box.
Here is my code:
$(document).ready(function() {
var increment = 0;
var artist_to_compare = new Set();
$(document).on("change", ".checkbox", function() {
increment += this.checked ? 1 : -1;
if (!this.checked) {
// // delete the artist from the list of comparison
$(element_to_delete).remove();
artist_to_compare.delete(this.name);
var element_to_delete = "." + this.name;
console.log(element_to_delete);
} else {
// Add the artist to the list of comparison
artist_to_compare.add(this.name);
var element_to_add = '<p class="' + this.name + '">' + this.name + '</p>';
console.log(element_to_add);
$(".artistToCompare").after(element_to_add);
}
if (increment >= 2) {
console.log(artist_to_compare);
// enable the compare button
}
});
});
I am able to correctly add the element but I cannot remove it. Please help!
Upvotes: 0
Views: 48
Reputation: 44
Yes Rahul is right. You are using remove()
function to delete element_to_delete
before defining it. Checkout following code.
$(document).ready(function() {
var increment = 0;
var artist_to_compare = new Set();
$(document).on("change", ".checkbox", function() {
increment += this.checked ? 1 : -1;
if (!this.checked) {
// delete the artist from the list of comparison
var element_to_delete = "." + this.name;
console.log(element_to_delete);
$(element_to_delete).remove();
artist_to_compare.delete(this.name);
} else {
// Add the artist to the list of comparison
artist_to_compare.add(this.name);
var element_to_add = '<p class="' + this.name + '">' + this.name + '</p>';
console.log(element_to_add);
$(".artistToCompare").after(element_to_add);
}
if (increment >= 2) {
console.log(artist_to_compare);
// enable the compare button
}
});
});
Upvotes: 0
Reputation: 2474
You have written $(element_to_delete).remove();
before defining element_to_delete
artist_to_compare.delete(this.name);
var element_to_delete = "." + this.name;
console.log(element_to_delete);
$(element_to_delete).remove();
Upvotes: 2