0

For my little project I want to have TextAreas and the textAreas should be generated in a for loop.


HTML

<h2>Settings for new Code:</h2>

<p>Amount of Checks:</p>
<input id="NumOfButtons"
       name="NumOfButtons"
       pattern=""
       size="30"
       spellcheck="false"
       title="amount of Checks"
       value="">

<script>

    let input = document.getElementById("NumOfButtons");
    input.addEventListener("keyup", function (event) {
        let listTA;
        if (event.keyCode === 13) {
            event.preventDefault();
            var x = parseInt(document.getElementById("NumOfButtons").value);
            listTA = new Array(x);
            for (let i = 0; i < x; ++i) {
                var textarea = document.createElement("textarea");
                textarea.name = "TextArea";
                textarea.maxLength = "100";
                listTA[i] = textarea;
                input.appendChild(textarea);
            }
        }
    });
</script>

The output should be a the amount of TextAreas which had been typed into the already existing textArea.

  • 1
    And the problem is what exactly? – Andreas Jul 17 '19 at 12:00
  • It doesn't work, it is stuck in the for loop somewhere –  Jul 17 '19 at 12:01
  • 1
    It doesn't work is not a helpful/insightful description: What is supposed to happen? What happens instead? Any errors in the console? What have you tried to fix the problem ([How can I debug my JavaScript code?](https://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code))? – Andreas Jul 17 '19 at 12:03
  • What is supposed to happen, a bunch of textAreas should be added under the already existing one. What happens instead: nothing no error no hints. I now even have tried to debug it, still nothing –  Jul 17 '19 at 12:08

1 Answers1

1

The answer is simple: a HTML <input> element is not a container - it can't hold child elements. What you want to do instead is create an empty <div> and append the textareas to it.

let input = document.getElementById("NumOfButtons");
input.addEventListener("keyup", function(event) {
  let listTA;
  if (event.keyCode === 13) {
    event.preventDefault();
    var x = parseInt(document.getElementById("NumOfButtons").value);
    listTA = new Array(x);
    for (let i = 0; i < x; ++i) {
      var textarea = document.createElement("textarea");
      textarea.name = "TextArea";
      textarea.maxLength = "100";
      listTA[i] = textarea;
      document.getElementById("theDiv").appendChild(textarea);
    }
  }
});
<h2>Settings for new Code:</h2>

<p>Amount of Checks:</p>
<input id="NumOfButtons" name="NumOfButtons" pattern="" size="30" spellcheck="false" title="amount of Checks" value="">
<div id="theDiv">
</div>
obscure
  • 11,916
  • 2
  • 17
  • 36