Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove array from javascript object

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);
});
like image 555
Sam32 Avatar asked Feb 09 '16 15:02

Sam32


1 Answers

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()
        }
    });
    ....
like image 198
charlietfl Avatar answered Oct 09 '22 07:10

charlietfl