简体   繁体   中英

How to disable HTML/JavaScript form if JavaScript is disabled in browser

First off the bat I am new to this an really trying my best to understand how this works. I have the following simple login form that leads to a homepage if the right login credentials are submitted. However when run in Firefox with JavaScript disabled the login credentials are ignored and my homepage is displayed anyway no matter what login details I provide. I have created a message in between <noscript></noscript> which fires when JavaScript is disabled. What I would like to achieve is that the warning message displays only and that the form etc. is disabled and not displayed until the login page is reloaded with JavaScript enabled. Can someone please help me with this? It is much appreciated!! My code is

<!doctype html>
<!-- This is is the main start page saved in index.html -->
<html lang="en-US">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>

<h2>Login details</h2>

<noscript>
        <h3>Before you login</h3>
        <p>JavaScript needs to run for this site to work properly.<br />
        Please activate JavaScript in your browser<br />
        and reload this page to login.
        </p>
</noscript>

<form id="myForm" name="login" onsubmit="return validateFormOnSubmit()" action="http://localhost:8080/index.html" method="post">
<fieldset>
  <label for="username">Username:</label><br>
  <input type="text" id="username" name="username"><br>
  <label for="password">Password:</label><br>
  <input type="password" id="password" name="password"><br><br>
  <input type="submit" value="Submit">
 </fieldset>
</form>
</body>
</html>

<script>
        function validateFormOnSubmit() {
        var un = document.login.username.value;
        var pw = document.login.password.value;
        var username = "username"
        var password = "password"
        if ((un == username) && (pw == password)) {
                return true;
        }
        else {
                alert ("Login was unsuccessful, please check your username and password");
                return false;
        }
}
</script>

You can achieve this without adding extra JavaScript. You can use a <noscript> tag also in the <head> , so you are able to hide this with CSS:

…
<head>
   …
   <noscript>
       <style>
           #myForm { 
              display: none 
           }
       </style>
   </noscript>
</head>
…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM