Context
I'm trying to implement a feature so that when the user clicks on a checkbox within a table, the attribute value
and data-title
of the checkbox should be stored in a JS object literal named selected
as a new key-value pair array element.
In case the user clicks a second time on the same checkbox, the corresponding array element should be removed.
Issue
The first time a checkbox is clicked, an array is created in object selected
as intended.
However, when the same checkbox is clicked a second time, instead of removing the corresponding array, a new one (repeated) is added.
Code
var selected = {items:[]};
$('#table').on('click', 'input[type="checkbox"]', function() {
var found = false;
$.each(selected.items, function(i, val) {
if (val.key == $(this).attr("value")) {
selected.items.splice(i ,1);
found = true;
return false; //step out of each()
}
});
if (found == false) {
selected.items.push({key: $(this).attr("value"), value: $(this).attr("data-title")});
}
console.log(selected);
});
You have the wrong context of this
inside each
. it is no longer the element in the click handler
Try
$('#table').on('click', 'input[type="checkbox"]', function() {
var found = false;
var value = $(this).val();// store value from `this` before entering `each`
$.each(selected.items, function(i, val) {
if (val.key == value) {
selected.items.splice(i ,1);
found = true;
return false; //step out of each()
}
});
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With