What I am trying to make is a system that if you check a checkbox, some text appears in a text-area. When you uncheck it, the text disappears. Now I got most of the code working, if you check a checkbox some text will appear, and if you uncheck it the text will disappear.
However, the commas stay, so I am left with a text-area with loads of commas.
code :
let text = [];
let counter = 0;
function boxChecker(a, b) {
let checkBox = document.getElementById("myCheck" + a);
let textarea = document.getElementById("textarea");
for (var i = 0; i < counter + 1; i++) {
text[counter] = b;
}
counter++;
if (checkBox.checked == true) {
textarea.value = text;
} else {
text.pop();
for (var i = 0; i < text.length; i++) {
if (text[i] === b) {
text.splice(i, 1);
}
}
}
textarea.value = text;
}
Here's what I get right now:

Give all the checkboxes a common class. Get the values of all the checked ones and display that, rather than using function parameters to pass the checkbox number and value to display.
function boxChecker() {
let allValues = Array.from(document.querySelectorAll(".myCheck:checked")).map(el => el.value);
document.getElementById("textarea").value = allValues.join(",");
}
The problem is when you assign array element to an index, it keeps other empty elements before it in the array causing the commas.
text[counter] = b;
Instead you could just push the element in the back of the array.
let text = [];
let counter = 0;
function boxChecker(a, b) {
let checkBox = document.getElementById("myCheck" + a);
let textarea = document.getElementById("textarea");
text.push(b);
if (checkBox.checked == true) {
textarea.value = text;
} else {
text.pop();
for (var i = 0; i < text.length; i++) {
if (text[i] === b) {
text.splice(i, 1);
}
}
}
textarea.value = text;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With