2

I am trying to output a line with the javascript Document.Write function, however, on Submitting the form, the line just flashes and disappears

any thoughts?

<!DOCTYPE html>    
<html>
    <head>
        <title>Form Validation</title>
    </head>
    <body>

        <script type="text/javascript">
            function checkAge() { 
                var x = document.forms['myForm']['age'].value;
                if(x < 18) {
                    document.write("<p>You are too Young. Form NOT submitted</p>");
                } else {
                    document.write("Form sent successfully");
                }
            }

            function tips() {
                alert("Please enter your Name in the name Box, \nand Your age in the Age box.\nYou have to be Over 18 to submit the form");
            }
        </script>

        <form id="myForm" action="formvalidation.html" onsubmit="checkAge();">    
            Name: <input type="text" name="text" id="name">
            Age: <input type="text" name="age" id="age">
            <input type="submit" value="Submit">
            <input type="button" value="Help" id="hBtn" onclick="tips();">
        </form>
    </body>
</html>
Bhavesh G
  • 2,844
  • 4
  • 35
  • 63
GDesigns
  • 285
  • 3
  • 4
  • 11

2 Answers2

3

You can't use document.write() to print on current page.

Calling document.write() will automatically call document.open() which clears the current document and thus your present content is cleared.

Alternatively you can use an html <div id="result"></div> and change it's value like this,

document.getElementById("result").innerHTML = "Some Text";
Bhavesh G
  • 2,844
  • 4
  • 35
  • 63
0

Return false on the handler to not make the page refresh on submit:

 <form id="myForm" action="formvalidation.html" onsubmit="checkAge();return false;">  
Dmitry Sadakov
  • 2,080
  • 2
  • 19
  • 31