Remove array from javascript object

Context

I am trying to implement such a function that when a user clicks a checkbox in a table, the value and data-title attribute of this checkbox should be stored in the JS object literature named selected as a new element of the key-value pairs array.

If the user clicks the same flag a second time, the corresponding array element must be deleted.

Question

The first time you click the check box, an array is created in the selected object, as expected.

However, when the same flag is clicked a second time, instead of deleting the corresponding array, a new (repeated) one is added .

the 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); }); 
+8
javascript jquery arrays checkbox
source share
3 answers

You have the wrong this context inside each . this is no longer an 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() } }); .... 
+6
source share

Firstly, I would recommend using a key-value-pair object, as this is easier to search for.

 var selected = { items : {} }; 

this way you will access the selected items using

 selected.items[my.key] 

maybe something 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]; }); 
+3
source share

how about this:

 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() }); 
0
source share

All Articles