user3611244
user3611244

Reputation: 11

Javascript :: New lines in textarea

In my HTML file I have this snippet of code:

<textarea class="form-control" id="textfield" rows="10"></textarea>

And in my Javascript file I have this:

    input1 = document.getElementById('input1').value;
    input2 = document.getElementById('input2').value;
    textfield = document.getElementById('textfield');

    if(document.getElementById('tmkbSelect').value == "option1") {
        document.getElementById('tmkb').innerHTML = "Tafel";
        for(input2i=0;input2i<20;input2i++){
            document.getElementById('textfield').value = input1+" "+"*"+" "+input2i+" "+"="+" "+input1*input2i;
        }
    }

I'm basically trying to create a multiplication table. It works, but not quite.

The javascript code is in a function and I call that function using a button, but the problem is that the output is this:

3 * 19 = 57

I want it to be:

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

And so on, how do I do this? I need to do this using only Javascript.

Upvotes: 0

Views: 109

Answers (3)

Manwal
Manwal

Reputation: 23816

Use ShortHand operator for adding content to textarea.

document.getElementById("test").value += "\n 1";

Demo

Upvotes: 1

Guffa
Guffa

Reputation: 700152

You need to concatenate the strings and then put them in the textarea.

You can add the strings to an array, and then concatenate them after the loop and put them in the textarea:

var lines = [];
for(input2i=0;input2i<20;input2i++){
  lines.push(input1+" "+"*"+" "+input2i+" "+"="+" "+input1*input2i);
}
document.getElementById('textfield').value = lines.join('\n');

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328536

In the loop, you assign the value:

... .value = input1+...

That means you overwrite the content every time. You need to append instead:

var content = '';
...
content += input1+...
...
document.getElementById('textfield').value = content;

Note the +=.

Don't forget to add '\n' after each line or everything will be in one line.

Upvotes: 0

Related Questions