Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading