Reputation: 117
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);
});
Upvotes: 8
Views: 97
Reputation: 3593
how about this one:
var selected = { items:[] };
$('#table').on('click', 'input[type="checkbox"]', function() {
selected.items = $('#table input[type="checkbox"]:checked').map(function(){
return {
key: $(this).attr('value'),
value: $(this).attr('data-title')
}
}).toArray()
});
Upvotes: 0
Reputation: 8407
First, I would recommend to use a key-value-pair object, as it is way easier for lookups.
var selected = { items : {} };
this way you would access your selected items using
selected.items[my.key]
maybe somethink like this...
var selected = {items:{}};
$('#table').on('change', 'input[type="checkbox"]', function() {
var checked = $(this).is(":checked"),
title = $(this).data("data-title"),
value = $(this).val();
if (checked && !selected.items[value])
selected.items[value] = title;
else if (!checked && !!selected.items[value])
delete selected.items[value];
});
Upvotes: 3
Reputation: 171679
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()
}
});
....
Upvotes: 6