简体   繁体   中英

Append elements to text box in new line using HTML DOM

Suppose i have textbox :-

<input type="text" name="content"  id="content"/>

And i am trying append text to this input box in the following manner:-

document.getElementById("content").value+= "A";

The output is something like:-

AAAA....

Each time, the text is getting appended in the same line, how can make the text to append each time to the new line? Like that of below.

A
A
A
.
.

Instead of an input type text, you can use a text area and then style it to look like a text box.

<textarea name="textarea_content" id="tx_content"></textarea>

document.getElementById("tx_content").value+= "A\n";
document.getElementById("tx_content").value+= "A\n";

JSFiddle: https://jsfiddle.net/sx7t3ykc/

The input textbox will support one single line. not multiple lines. that is it's behaviour. That's why your text is shown in a single line.

If you need multiple lines, then you need to use <textarea></textarea> element

input is used for a single line. Try using textarea .

Refer code below:

<textarea type="text" name="content"  id="content">
</textarea>

and js will be like this:

document.getElementById("content").value+= "A\n";

I have made you an example that appends a new "A" char every 5 seconds. I use textarea instead of the input tag.

 setInterval(appendNewChar, 5000) function appendNewChar() { document.getElementById("myTextArea").value += "A\\n"; } 
 <textarea id="myTextArea"></textarea> 

As @GuyFromChennai said, you have to use tag instead of , also, writing '\\n' will make the line break, I tried this:

<textarea name="content"  id="content"></textarea>

for (let i=0; i<3; i++){
   document.getElementById("content").value+= "A\n"";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM