Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

commas in arrays, javascript

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:

enter image description here

like image 564
mattijn325 Avatar asked Dec 18 '25 21:12

mattijn325


2 Answers

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(",");
}
like image 179
Barmar Avatar answered Dec 21 '25 10:12

Barmar


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;
}
like image 23
Chitrang Avatar answered Dec 21 '25 10:12

Chitrang