hellomello hellomello - 1 month ago 6
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 = [];
$('.media-search').mouseenter(function(){
var $this = $(this);
$this.toggleClass('highlight');
}).mouseleave(function(){
var $this = $(this);
$this.toggleClass('highlight');

}).on('click',function(){
var dataid = $(this).data('id');

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


});

Answer

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) {
  selectArr.push(dataid);
} else {
  selectArr.splice(idx, 1);
}
Comments