Delete variable provided when unchecking Checkbox

1

I have a code that saves in a textarea values from a checkbox, but I can not get the value to be cleared from the textarea when the checkbox is unchecked.

var checkbox = document.getElementsByName('CP[]');
var teste = [];

function addCheck() {
    for (var i = 0; i < checkbox.length; i++) {
        if (checkbox[i].checked == true)
            teste[i] = checkbox[i].value;
    }
	
    document.getElementById("cps").innerHTML = teste;
    var textarea = document.getElementById("cps").value;
}
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="A">
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="B">
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="C">
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="D">
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="E">

<br />

<textarea name='cps' id='cps' cols='8' rows='1' value=''></textarea>
    
asked by anonymous 24.05.2016 / 18:44

1 answer

2

You have to make some changes:

  • teste[i] = checkbox[i].value; must be teste.push(checkbox[i].value); otherwise you will be creating empty positions within the array

  • ..."cps").innerHTML = teste; must be ..."cps").innerHTML = teste.join(','); . It is not critical, but as it is a conversion from Type to gross.

  • puts var teste = []; before for to re-initialize the variable with an empty array

Example:

var checkbox = document.getElementsByName('CP[]');
var cps = document.getElementById("cps");

function addCheck() {
  var teste = [];
  for (var i = 0; i < checkbox.length; i++) {
    if (checkbox[i].checked == true) teste.push(checkbox[i].value);
  }
  cps.innerHTML = teste.join(',');
}
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="A">
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="B">
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="C">
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="D">
<input name='CP[]' id='CP01' type='checkbox' onclick='addCheck()' value="E">
<br />
<textarea name='cps' id='cps' cols='8' rows='1' value=''></textarea>
    
24.05.2016 / 19:07