Click here to Skip to main content
14,298,693 members
Rate this:
Please Sign up or sign in to vote.
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

To add a line-break in the text content, you need to use '\n':
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[^]:
<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:
<!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>
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100