Remove array item when unchecking checkbox

Asked

Viewed 168 times

3

I’m taking the value of a checkbox and putting in an array valores, My question is: how, when unchecking the checkbox, to remove this value from my array? Because if I check and uncheck the checkbox 10 times it will put the value in the array 10 times.

var checkbox = document.getElementById("checkbox");
var valores = [];

checkbox.onchange = function(){
    valores.push(event.target.value);
}

2 answers

4


Create a condition to remove if it already exists in your array:

if (valores.indexOf(event.target.value) === - 1) {
    // Se o evento não está presente no vetor, nós o adicionamos
    valores.push(event.target.value);
} else {
    // Se o evento está presente no vetor, nós o removemos
    valores.filter(function(value, index, arr){
        return value !== event.target.value;
    });
}
  • the function pop removes the last array item and not a specific item...

  • True, it was inattentive. Amended and thank you!

1

first of all you need to validate if the item is already in your array

value_included = valores.include(event.target.value);
is_checked = event.target.checked;

// o valor já esta no array porem o checkbox não esta selecionado
if (value_included && !is_checked) {
    position = valors.indexOf(event.target.value);
    valores.splice(position, 1);
    return
}

// o valor não esta no array e o checkbox esta selecionado
if (!value_included && is_checked) {
    valores.push(event.target.value);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.