Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }


}); 
like image 542
hellomello Avatar asked Feb 09 '13 01:02

hellomello


1 Answers

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);
}
like image 120
Guffa Avatar answered Oct 21 '22 21:10

Guffa