Do not use id
for the elements, because you will be duplicating id’s on both buttons, which is wrong in HTML. Instead use dataset data-id
, for example:
<button class="btnlike" data-id="1">LIKE</button>
<button class="btnnotlike" data-id="1">NOT LIKE</button>
If using the tag button, as above, use value
instead of
data-id
.
Use the method $.grep() jQuery to filter arrays by removing, if any, the value of the button clicked on the other array.
That is, you check whether the value exists in the array with .$inArray
and then uses the $.grep
to remove the value from the other array. The code is very simple, as shown below. You can even improve by joining the events in the two buttons in one, but I put them in separate even to make it easier to read.
//DEFINE ARRAYS
like = new Array();
notlike = new Array();
//SE CLICA NO btnlike VAI PARA ARRAY LIKE
$(".btnlike").on("click", function() {
var valor = $(this).data("id");
if(!~$.inArray(valor, like)){
like.push(valor);
}
notlike = $.grep(notlike, function(v){
return v != valor;
});
// daqui pra baixo é só para ilustração. Não inclua
console.clear();
console.log("LIKE: ", like.join(","));
console.log("NOTE LIKE: ", notlike.join(","));
});
//SE CLICA NO btnnotlike VAI PARA ARRAY NOTLIKE
$(".btnnotlike").on("click", function() {
var valor = $(this).data("id");
if(!~$.inArray(valor, notlike)){ // verifica se já existe
notlike.push(valor); // adiciona na array
}
like = $.grep(like, function(v){ // remove da outra array
return v != valor;
});
// daqui pra baixo é só para ilustração. Não inclua
console.clear();
console.log("LIKE: ", like.join(","));
console.log("NOTE LIKE: ", notlike.join(","));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1. <button class="btnlike" data-id="1">LIKE</button>
<button class="btnnotlike" data-id="1">NOT LIKE</button>
<br><br>
2. <button class="btnlike" data-id="2">LIKE</button>
<button class="btnnotlike" data-id="2">NOT LIKE</button>
<br><br>
3. <button class="btnlike" data-id="3">LIKE</button>
<button class="btnnotlike" data-id="3">NOT LIKE</button>
cool, I’ll test it here
– Leandro Marzullo
Good luck brother! Thumbsup if you roll ;)
– Leonardo Negrão