Psl
Psl

Reputation: 3920

Jquery code to remove item from array

I have a list of checkboxes while selecting checkboxes i have to add the values to arrays and while unchecking i have to remove that from array.

following code am using. but it is not deleting while unchecking

<tr><td class="tdstyleSelect"><input type="checkbox" name="joblist" onclick="toNfroVmps(this.id);" id="' + i + '" checked>

var toNfroVmps = function(id) {
    if($('#' + id).is(':checked')) 
        elementIds.push(id);   
    else    
        delete elementIds[elementIds.indexOf(id)]
}

Upvotes: 1

Views: 250

Answers (2)

raina77ow
raina77ow

Reputation: 106483

Use Array.splice (which is, btw, a native JS method):

var index = elementIds.indexOf(id);
if (index !== -1) {
  elementIds.splice(index, 1);
}

You might consider using hashes (instead or a plain Array) to store your data: with each key corresponding to an ID, and value either true or false.

var elementIds = {
  el1: true,
  el2: true,
  el3: false
  // ...
};

This way adding/removing an element will be even more straight-forward:

elementIds[id] = $('#' + id).is(':checked'); // either true or false

... and you still will be able to process this hash as array, using various jQuery list comprehension functions. For example, that's how you collect ids of all the checked elements:

var checkedIds = $.grep(elementIds, function(el) { return el; });

Upvotes: 9

MisterBla
MisterBla

Reputation: 2395

You can use the splice method to remove array items.

var toNfroVmps = function(id) 
{
    if($('#' + id).is(':checked')) 
        elementIds.push(id);   
    else
    {
        // Select the index
        var i = elementIds.indexOf(id);

        // Check if the index exists, to prevent any errors that might happen
        // If exists, delete
        if(i !== -1)
            elementIds.splice(i, 1);

    }
}

Upvotes: 1

Related Questions