Delete variable provided when unchecking Checkbox

Asked

Viewed 29 times

1

I have a code that saves in a textarea values from a checkbox, but I cannot make the value be deleted 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>

1 answer

2


You gotta make some changes:

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

  • ..."cps").innerHTML = teste; must be ..."cps").innerHTML = teste.join(',');. It is not fundamental, but as it is a conversion of Type brute.

  • puts var teste = []; before the 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>

  • 1

    That’s right, thank you very much!

  • @Great rock. See you soon.

Browser other questions tagged

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