简体   繁体   English

使用HTML DOM在新行中将元素追加到文本框中

[英]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/ 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 如果需要多行,则需要使用<textarea></textarea>元素

input is used for a single line. input用于单行。 Try using textarea . 尝试使用textarea

Refer code below: 参考下面的代码:

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

and js will be like this: 和js将是这样的:

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

I have made you an example that appends a new "A" char every 5 seconds. 我为您提供了一个示例,该示例每5秒追加一个新的“ A”字符。 I use textarea instead of the input tag. 我使用textarea代替了输入标签。

 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: 正如@GuyFromChennai所说,您必须使用标记而不是,而且,写'\\ n'将使换行符中断,我尝试这样做:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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