0

I have been working on a simple login page where I accept values and print them back. I have written a function in javascript to store input values from text box. I have added two print statements to just check till where my program works. Here is my script.

<html>

<head>
    <link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
    <meta charset="UTF-8">

    <title>Home| Login</title>
</head>


<body>
    <script type="text/javascript">
        function init() {
            document.write("Reached Point 1");
            document.write(document.getElementById("username").value);
            var password = document.getElementById("password").value;
            document.write("Reached Point 2");
        }
    </script>
    <div class="logo"></div>
    <div class="login-block">
        <h1>Login</h1>
        <input type="text" value="" id="username" />
        <input type="text" value="" id="password" />
        <button onclick="init()">Submit</button>

    </div>
</body>

</html>

Reached Point 1 is getting printed on clicking the button but the username and Reached Point 2 are not getting printed.

1
  • Hi there. Maybe document.write is not the best way to go about it. Try console.log("reached point 1") instead. Commented Jan 7, 2016 at 8:27

1 Answer 1

2

You can't use document.write once the document has completed loading. If you do, the browser will open a new document that replaces the current. And as the document is replace there won't be any functions and HTML Elements and anything. Instead use innerHTML to put HTML code inside an element.

        function init() {
            document.getElementById("description").innerHTML += "Reached Point 1";
            document.getElementById("description").innerHTML +=  document.getElementById("username").value;
            var password = document.getElementById("password").value;
            document.getElementById("description").innerHTML += "Reached Point 2";
        }
    <div class="logo"></div>
    <div class="login-block">
        <h1>Login</h1>
        <input type="text" value="" id="username" />
        <input type="text" value="" id="password" />
        <button onclick="init()">Submit</button>
        <p id="description"></p>
    </div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.