hellomello hellomello - 1 year ago 64
jQuery Question

jQuery: checking if value is in array, if so, delete, if not, add

I'm trying to check if there's a value in the array already. If the value does not exists in array, then it should be added into the array, if the value already exists, it should be deleted.

var selectArr = [];
var $this = $(this);
var $this = $(this);

var dataid = $(this).data('id');

if(selectArry){ // need to somehow check if value (dataid) exists.
selectArr.push(dataid); // adds the data into the array
// somehow remove the dataid value if exists in array already


Answer Source

Use the inArray method to look for a value, and the push and splice methods to add or remove items:

var idx = $.inArray(dataid, selectArr);
if (idx == -1) {
} else {
  selectArr.splice(idx, 1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download