Rob
Rob

Reputation: 19

How duplicate text in textarea?

So I need a code to repeat a text which can be set the amount in an input.

So when the user write number 3, I want the content of the textarea like this:

Hello World(1) Hello World(2) Hello World(3)

But it appears like this:

Hello World(3)

Actually, I can use text.repeat(3). But I want there to be a number behind Hello World, so I use for loop.

Here's my code:

<input onchange="dup()" type="number" id="inp">
    <br>
    <br>
    <textarea id="txtarea"></textarea>
    <script>
        function dup(){
            var num = document.getElementById("inp").value;
            for (let i = 0; i < num; i++){
                document.getElementById("txtarea").innerHTML = "Hello World("+num+")"
            }

        }
    </script>

Upvotes: 0

Views: 135

Answers (3)

errixed
errixed

Reputation: 133

use this

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>Document</title>
</head>
<body>
<input onchange="dup()" type="number" id="inp">
    <br>
    <br>
    <textarea id="txtarea"></textarea>
    <script>
        function dup(){
            var num = document.getElementById("inp").value;
            for (let i = 1; i <= num; i++){
                document.getElementById("txtarea").innerHTML += "Hello World("+i+")"
            }

        }
    </script>

the problem was this

you should use document.getElementById("txtarea").innerHTML += "Hello World("+i+")" instead of this document.getElementById("txtarea").innerHTML = "Hello World("+num+")"

second:

Upvotes: 0

MeL
MeL

Reputation: 1269

You could create an empty object, then loop over the inputs and add to it. Then display the values from the object, like this:

const textArea = document.getElementById("txtarea");
const obj = {}
   function dup(){
            const num = document.getElementById("inp").value;
            for (let i = 0; i < num; i++){
            obj['text'+i] = `Hello World(${i+1})`;
               
            }
             textArea.innerHTML = Object.values(obj).join(' ');
            };
<input onchange="dup()" type="number" id="inp">
    <br>
    <br>
    <textarea id="txtarea"></textarea>

Upvotes: 0

Larry-Larriee
Larry-Larriee

Reputation: 27

When you're running a for-loop like this, you're setting the txtarea id text to have an innerHTML output of Hello World(1), then change to Hello World(2), then change to Hello World(3), hence why you only see Hello World(3).

Instead of having document.getElementById("txtarea").innerHTML = "Hello World("+num+")" try replacing = with +=

Upvotes: 1

Related Questions