Pass and Remove Value of Checkboxes to input

1

They could help me, I have 3 checkboxes and an input.

By clicking on the checks, pass the value to the input, until then everything is fine.

What I need is that when a check is unchecked only that value that passed to the input is deleted.

<input type="checkbox" id="checkbox" name="checkbox" onclick="campo.value += (this.checked) ? this.value:'' " value="Valor1" />
<input  type="checkbox" id="checkbox2" name="checkbox2" onclick="campo.value += (this.checked) ? this.value:'' " value="Valor2" />
<input  type="checkbox" id="checkbox3" name="checkbox3" onclick="campo.value += (this.checked) ? this.value:'' " value="Valor3" />

<input type="text" name="campo" id="campo" /> 
    
asked by HaGeN BeTa 22.11.2018 в 17:16
source

1 answer

2

Instead of adding the value of the individual checkbox, when you click check the status of all the checkboxes to create the result, this is what I mean:

var checkboxes = document.querySelectorAll('input[type=checkbox]');
var text = document.getElementById('campo');

function checkboxClick(event) {
  var valor = '';
  for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].checked) {
      valor += checkboxes[i].value;
    }
  }
  campo.value = valor;
}

for (var i = 0; i < checkboxes.length; i++) {
  checkboxes[i].addEventListener('click', checkboxClick);
}
<input type="checkbox" value="Valor1" />
<input  type="checkbox" value="Valor2" />
<input  type="checkbox" value="Valor3" />

<input type="text" name="campo" id="campo" />
    
answered by 22.11.2018 в 17:30