B. Gillanders
B. Gillanders

Reputation: 27

Why won't this code work to get the text from a HTML textbox and display it in a paragraph?

Why won't the code display the text from the textbook in the paragraph tag? I tried to take the code from the text box by using the onclick command and the function getVal() but it won't work.

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <script src="test.js">
            function getVal1(){
                var text = document.getElementById('text').value;
                var par = document.getElementById('par');
                par.innerHTML=text
            }
        </script>
    </head>
    <body>
        <form>
            <input type="text" id="text">
            <input type="submit" value="Submit" onclick="getVal1()"> 
        </form>
        <p id="par"></p>
    </body>
</html>

Upvotes: 2

Views: 31

Answers (1)

d-h-e
d-h-e

Reputation: 2558

It cant work because you submit (which includes a reload) of the page. Take a input type="button"instead.

function getVal1() {
  var text = document.getElementById('text').value;
  var par = document.getElementById('par');
  par.innerHTML = text
}
<!DOCTYPE html>
<html>

<head>
  <title>Test</title>

</head>

<body>
  <form>
    <input type="text" id="text">
    <input type="button" value="Submit" onclick="getVal1()">
  </form>
  <p id="par"></p>
</body>

</html>

Upvotes: 1

Related Questions