spaceguy
spaceguy

Reputation: 37

how to submit a form in javascript when a user presses the enter keyboard

what code or what can i add to my html. or js. file to make it submit the form when someone presses the enter keyboard? this my html file

<!DOCTYPE html>
<html>
<head>
  <title>test Form</title>
  <script type="text/javascript" src="main.js"></script>
</head>
<body>


 <h3>Start Here</h3>
   UserName: <input type="text" id="user"><br>

    Master Code: <input type = "password" id = "pass"><br><br>


   <input type="submit" value="Submit" onclick= "check()">
</body>
</html>

and this is my external javascript file

function check()
{
var t = document.getElementById("user").value;
var m = document.getElementById("pass").value;

 if (t === "username")
 {
    if(m === "password")
    {
        document.write("SUCCESS!")
    }

    else if (m != "tete")
    {
        document.write("wrong password");
    }
 }

 else {
    document.write("ERROR!")
 }

}

Upvotes: 0

Views: 329

Answers (1)

keenthinker
keenthinker

Reputation: 7820

There are a few things that you need to add resp. change in your code, in order to work as expected:

  • wrap your fields and the submit button into a form
  • cancel the form submition event
  • don't write directly to the document, but use an output panel, a div for example. This way you could even build a very simple log panel.

The code with the changes from above:

<!DOCTYPE html>
<html>
<head>
  <title>test Form</title>
  <script type="text/javascript">
    function check()
    {
        var t = document.getElementById("user").value;
        var m = document.getElementById("pass").value;
        // get the "output" panel
        var o = document.getElementById("output");

        if (t === "username")
        {
            if(m === "password")
            {
                // add text to the div as simple log
                o.innerHTML += "SUCCESS!<br />";
            }
            else if (m != "tete")
            {
                o.innerHTML += "wrong password<br />";
            }
        }
        else 
        {
            o.innerHTML += "ERROR!<br />";
        }
        // bind to the submit event and cancel it, to prevent realod!
        document.getElementById('form1').onsubmit = function() {
            return false;
        }
    }
  </script>
</head>
<body>
    <!-- wrap your code in a form that gets submited on enter keypress -->
    <form id="form1" action="#" method="post">
        <h3>Start Here</h3>
        UserName: <input type="text" id="user"><br>
        Master Code: <input type = "password" id = "pass"><br><br>
        <input type="submit" value="Submit" onclick= "check()">
        <div id="output"></div>
   </form>
</body>
</html>

The data is submitted when the user presses either the enter key or the submit button.

Upvotes: 1

Related Questions