13

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
    }


}); 
0

3 Answers 3

36

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Simple JavaScript program to find and add/remove the value in the array

var myArray = ["cat","dog","mouse","rat","mouse","lion"]
var count = 0; // To keep a count of how many times the value is removed 
for(var i=0; i<myArray.length;i++) {
    //Here we are going to remove 'mouse'
    if(myArray[i] == "mouse") {
        myArray .splice(i,1);
        count = count + 1;
    }
}
//Count will be zero if no value is removed in the array
if(count == 0) {
    myArray .push("mouse"); //Add the value at last - use 'unshife' to add at beginning 
}

//Output
for(var i=0; i<myArray.length;i++) {
    console.log(myArray [i]); //Press F12 and click console in chrome to see output
}  

Comments

0
  function AddingOffences() {

var sendingcountry = ary.filter((item) => {
  return (item.Offence.toLowerCase().indexOf($("#ddl_OffencesByLocation option:selected").val()) > -1);
})
if (sendingcountry == "") {

  if ($("#txtPriceByLocation").val() == "") {
    alert("Please select price")
  } else {



    $("#Div_OffenceListByLoction").append("<li id=" + $("#ddl_OffencesByLocation option:selected").val() + ">" + $("#ddl_OffencesByLocation option:selected").text() + "<span>" + $("#txtPriceByLocation").val() + " kr" + "</span><span onclick='RemoveOffence(" + $("#ddl_OffencesByLocation option:selected").val() + ")' > Remove</span></li>");
    pushToAry($("#ddl_OffencesByLocation option:selected").val(), $("#txtPriceByLocation").val());
  }
  } else {
    alert("Allready Exist");
  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.