0

I have the following page with a javascript file, when the user enters the wrong username/password the message "wrong username password" is output to page; however, the message does not stay on the page. For some reason the page gets refresh.

<html>
  <head>
   <script src="letmein.js"></script>
  </head>
  <body>
  <h1 id="h1">JavaScript Test Page</h1>  
  <p id="p">Click the link to login into the application</p>
  <p>login</p>
  <form id="myForm" name="myForm" onSubmit="letmein();">
    <p>username:
    <input type="text" name="username">
    </p>
    <p>password:
    <input type="text" name="password">
      </p>
     <input type="submit" value="Login">    
  </form>
  <p id="hidden"></p>
  <a href="#" onClick="clear();">clear</a>  
  </body>
</html>

javascript file

var username = "admin";
var password = "letmein";
var counter = 0;

//login form authentication

    function letmein() {
      var formUser = document.forms['myForm']['username'].value;
      var formPass = document.forms['myForm']['password'].value;
      if(formUser === username && formPass === password) {
        window.open("file:///home/jorge/usersearch.html");    
      }
      counter++;
      document.getElementById("hidden").innerHTML = "Wrong username or password!"
      if(counter === 3) {
        alert("Access Denied!");
      }  
    }

    //close window
    function closeWindow() {
        close();
    };
miatech
  • 2,150
  • 8
  • 41
  • 78
  • 1
    You are not preventing the form's default action, which is making an HTTP request with the data to the provided target. – Felix Kling Sep 23 '15 at 16:23
  • 1
    When you submit a form, it goes to the action url. In this case, it is your current page, so it refreshes it. This should help here. http://stackoverflow.com/questions/16262797/html-form-action-and-onsubmit-issues – Hieu Le Sep 23 '15 at 16:23
  • look up preventDefault() – devlin carnate Sep 23 '15 at 16:24

2 Answers2

0

I think clicking the button submits the form. You need to return false on onSubmit in order to avoid submitting the form.

<html>
  <head>
   <script src="letmein.js"></script>
  </head>
  <body>
  <h1 id="h1">JavaScript Test Page</h1>  
  <p id="p">Click the link to login into the application</p>
  <p>login</p>
  <form id="myForm" name="myForm" onSubmit="letmein(); return false;">
    <p>username:
    <input type="text" name="username">
    </p>
    <p>password:
    <input type="text" name="password">
      </p>
     <input type="submit" value="Login">    
  </form>
  <p id="hidden"></p>
  <a href="#" onClick="clear();">clear</a>  
  </body>
</html>
Anuraag Vaidya
  • 827
  • 9
  • 16
0

You need to stop the form's default action. For example:

function letmein(e) {
  if(validationFails) {
    e.preventDefault();  //this will stop the form from submitting
  } 

}
devlin carnate
  • 8,309
  • 7
  • 48
  • 82