Open In App

How to add line breaks to an HTML textarea?

Last Updated : 09 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Line breaks in an HTML textarea refer to the inclusion of newline characters (\n) that separate lines of text within the textarea. When users press Enter or Return, a line break is created, making text easier to read and format within the form element.

The way of implementing line breaks differs from one platform to another. The following approach takes input text from HTML Textarea and adds line breaks using JavaScript.

Approach

This task can be achieved by using some predefined array and string functions provided by JavaScript. In the following code, the input from the text area is processed by JavaScript at the click of the submit button to produce the required output with line breaks.

  • JavaScript Functions: It Utilizes split() to break the input text into an array based on periods ('.') and join() method to concatenate the array elements with </br> for line breaks.
  • Textarea Input: Retrieves the text input from a <textarea> element in the HTML form using getElementById('a').value.
  • Event Handling: Executes the divide() function when the submit button is clicked, triggered by onclick=" divide()".
  • Output Display: It uses document.write() to display the modified text with added line breaks directly on the page.

Example: To demonstrate adding line breaks to an HTML text area using JavaScript.

html
<!DOCTYPE html>
<html>

<head>
    <title>line breaks to an HTML textarea</title>
</head>

<body>
    <form>
        ENTER TEXT:
        <br>
        <textarea rows="20" 
                  cols="50"
                  name="txt"
                  id="a">
      </textarea>
        <br>
        <br>
        <input type="submit" 
               name="submit" 
               value="submit" 
               onclick="divide()" />
    </form>
    <script type="text/javascript">
        function divide() {
            let txt;
            txt = document
                .getElementById('a').value;
            let text = txt
                .split(".");
            let str = text
                .join('.</br>');
            document.write(str);
        }
    </script>
</body>

</html>

Output:

LineBreak
line breaks to an HTML textarea example Output

Similar Reads