Click here to Skip to main content
15,895,667 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm creating a form that when each field is entered and you press submit, it provides all of the text on the page for you. However, all of the text continues onto the same line when submitted, I'm trying to submit a space between each text value (text1, text2..ex) For each box you enter, I'm trying to have them on separate lines.

I'm really new to all of this, if you could help me I'd appreciate it.

Thank you :)

What I have tried:

<!DOCTYPE html>
<html>
<head>
    <script>
        function testVariable() {
            var strText = document.getElementById("textone").value;          
            var strText1 = document.getElementById("textTWO").value;
 var result = strText + ' ' + strText1;
            document.getElementById('spanResult').textContent = result;
             
        }
    </script>
</head>
<body> 
    <input type="text" id="textone" value="• Name/ Title :" />
<br>
    <input type="text" id="textTWO" value="• Phone #: " />
<br><br>
    <button  onclick="testVariable()">Submit</button> <br />
    <span id="spanResult">

    </span>
   
     
</body>
</html>
Posted
Updated 5-Sep-19 8:35am

1 solution

To add a line-break in the text content, you need to use '\n':
JavaScript
var result = strText + '\n' + strText1;

However, most HTML elements ignore line-breaks and other spaces within their content.

You can either use a <pre> element[^]:
HTML
<pre id="spanResult"></pre>
Demo[^]

or you can set the white-space CSS property[^] to pre-line:
<style>
#spanResult {
    white-space: pre-line;
}
</style>
Demo[^]

Complete example:
HTML
<!DOCTYPE html>
<html>
<head>
    <script>
        function testVariable() {
            var strText = document.getElementById("textone").value;          
            var strText1 = document.getElementById("textTWO").value;
            var result = strText + '\n' + strText1;
            document.getElementById('spanResult').textContent = result;
        }
    </script>
    <style>
        #spanResult {
            white-space: pre-line;
        }
    </style>
</head>
<body> 
    <input type="text" id="textone" value="• Name/ Title :" />
    <br>
    <input type="text" id="textTWO" value="• Phone #: " />
    <br><br>
    <button  onclick="testVariable()">Submit</button> <br />
    <span id="spanResult"></span>
</body>
</html>
 
Share this answer
 
v2
Comments
Member 14580014 5-Sep-19 14:44pm    
Perfect, thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900