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);
});
checkedstate of the checkbox? I assume your array should represent the boxes that are currently checked.val.key == $(this).attr("value"). This likely (possibly due to the strangeness of equality in Javascript), never returns true. You should probably use === aswell. Debug your javascript and check thisthisequal to inside the$.eachcallback?