I am making use of Gridster widgets on webpage.Each widget is having a button on it which changes the color to red of widget after that is clicked.Once that button is pressed the parent element gets added to an array as well.
My overall aim
I want the parent element to go in array when user clicks the element and if he clicks the same elements it should come out of that array.
What I have tried so far
I am able to add the elements which are clicked in to the array but not able to remove the element from array which is clicked again.(also want to remove the red color if clicked for second time)
Just to check if the elements is present in an array or not I tried with this function
function checkIfArrayIsUnique(myArray)
{
for (var i = 0; i < myArray.length; i++)
{
for (var j = 0; j < myArray.length; j++)
{
if (i != j)
{
if (myArray[i] == myArray[j])
{
return false; // means there are duplicate values
}
}
}
}
return true; // means there are no duplicate values.
}
The problem
The function always returns true
even when same element is clicked twice
My Overall JS
var parentElement = [];
$(document).on("click", ".select-element", function() {
$(this).closest('li').attr("style", "background-color:red");
parentElement.push($(this).closest('li'));
console.log("Parent Element Array Length");
for (var i = 0; i < parentElement.length; i++) {
console.log(parentElement[i]);
}
});
$(document).on("click", "#check", function() {
alert(checkIfArrayIsUnique(parentElement));
});