Jquery code to remove item from array

Psl*_*Psl 1 javascript arrays jquery

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)]
}
Run Code Online (Sandbox Code Playgroud)

rai*_*7ow 9

使用Array.splice(也就是btw,一个本机JS方法):

var index = elementIds.indexOf(id);
if (index !== -1) {
  elementIds.splice(index, 1);
}
Run Code Online (Sandbox Code Playgroud)

您可以考虑使用哈希(而不是普通数组)来存储数据:每个键对应一个ID,值为true或false.

var elementIds = {
  el1: true,
  el2: true,
  el3: false
  // ...
};
Run Code Online (Sandbox Code Playgroud)

这样添加/删除元素将更加直截了当:

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

...你仍然可以使用各种jQuery列表理解函数将此哈希处理为数组.例如,这就是你如何收集所有已检查元素的ID:

var checkedIds = $.grep(elementIds, function(el) { return el; });
Run Code Online (Sandbox Code Playgroud)