乐闻世界logo
搜索文章和话题

How to add a new line in textarea element?

1个答案

1

In HTML, the textarea element is used for inputting multi-line text. If you need to add new lines in the textarea, there are typically two approaches to achieve this:

1. Directly using newline characters in HTML

By directly adding newline characters (\n) to the textarea's default value in HTML, the element already contains pre-defined new lines when the page loads. For example:

html
<textarea> First line text Second line text </textarea>

In this example, a new line exists between "First line text" and "Second line text" because HTML supports direct multi-line input for textarea content.

2. Dynamically adding with JavaScript

You can use JavaScript to dynamically add new lines to the textarea. This method is suitable when user interaction or other program logic requires adding lines at runtime. Here is an example:

html
<textarea id="myTextarea">Initial text</textarea> <button onclick="addNewLine()">Add new line</button> <script> function addNewLine() { var textarea = document.getElementById('myTextarea'); textarea.value += "\nNew added line"; } </script>

In this example, clicking the button calls the addNewLine() function, which retrieves the textarea element and appends a newline character followed by the new text line to its existing content.

Both methods are effective for adding new lines to the textarea, and the choice depends on your specific requirements and context.

2024年6月29日 12:07 回复

你的答案