检查用户是否输入了某些内容的功能

时间:2017-12-15 07:32:39

标签: javascript function require required

我在如何添加功能方面遇到了一些困难。有人可以告诉我如何添加一个能显示弹出消息的功能,说明"名称/密码字段为空" 这里的问题是如果我点击登录,而输入字段为空,它仍然说用户登录?即使他们是空的?我不能使用任何PHP功能。

   <html>
 <head>
<title>Week 9 Q&A Session - Form Demo</title>
  </head>
  <body>

<!--Registration form -->
<div>
    <h1>Registration</h1>
    <form onsubmit="registerUser()">
<input type="text" name="username" value="" id="name" required>
<input type="password" name="password" id="password" required>
<button type="submit">Submit</button>
</form>
</div> 

<!-- Login form -->
<div>
    <h1>Login</h1>
    <input type="text" name="username" value="" id="loginName">
    <input type="password" name="password" id="loginPassword">
    <button onclick="checkLogin()">Submit</button>
    <p id="LoginResult">Not logged in.</p>
</div> 

<!-- Rankings table will be inserted here -->
<div id="RankingsTable"></div>

<script>

    /* Does some basic checking of user data then stores
        user data in localStorage */
    function registerUser(){
        //Extract the name and password that the user has entered
        var nameInput = document.getElementById("name").value;
        var pwdInput = document.getElementById("password").value; 

        //Check that the name and password are not empty
        if(nameInput !== "" && pwdInput !== ""){
            //Create a JavaScript object to hold the user data.
            var usrObj = {};

            //Add user entered data to object
            usrObj.username = nameInput;
            usrObj.password = pwdInput;

            //Add a score field to object to support rankings table
            usrObj.topscore = 0;

            //Store a string version of the object in local storage.
            localStorage[nameInput] = JSON.stringify(usrObj);
        }
    }


    /* Checks that the username and password match the user name and password of a 
        registered user and provides feedback to user. */
    function checkLogin(){
        //Get a reference to the div where we will display the login result
        var loginResult = document.getElementById("LoginResult");

        //Extract the name and password that the user has entered
        var nameInput = document.getElementById("loginName").value;
        var pwdInput = document.getElementById("loginPassword").value; 

        //Output for debugging
        console.log("Login name: " + nameInput+ "; Login password" + pwdInput);

        //Check to see if we have data stored for this user
        if(localStorage[nameInput] === undefined){
            //No user found - provide feedback to user.
            loginResult.innerHTML = "User name incorrect";
            return;
        }

        //Check password
        //Get object that is stored for the user name.
        var usrObj = JSON.parse(localStorage[nameInput]);

        //Compare the entered password with the stored password
        if(pwdInput !== usrObj.password){
            //Incorrect password - provide feedback to user
            loginResult.innerHTML = "Password incorrect";
            return;
        }

        //If we have got this far, the username and password are correct

        //Record the user that has logged in using local storage.
        localStorage.loggedInUser = nameInput;

        //Provide feedback to user - you could also provide a logout button - see the example in my slides.
        loginResult.innerHTML = "User logged in.";
    }


    /* This function is called when a logged in user 
        plays the game and gets a score */
    function updateScore(newScore){
        //Get the JavaScript object that holds the data for the logged in user
        var usrObj = JSON.parse(localStorage[localStorage.loggedInUser]);

        //Update the user object with the new top score
        /* NOTE YOU NEED TO CHANGE THIS CODE TO CHECK TO SEE IF THE NEW SCORE
            IS GREATER THAN THE OLD SCORE */
        usrObj.topscore = newScore;

        //Put the user data back into local storage.
        localStorage[localStorage.loggedInUser] = JSON.stringify(usrObj);
    }


    /* Loads the rankings table.
        This function should be called when the page containing the rankings table loads */
    function showRankingsTable(){
        //Get a reference to the div that will hold the rankings table.
        var rankingDiv = document.getElementById("RankingsTable");

        //Create a variable that will hold the HTML for the rankings table
        var htmlStr = "";

        //Add a heading 
        htmlStr += "<h1>Rankings Table</h1>";

        //Add the table tag
        htmlStr += "<table>";

        //Work through all of the keys in local storage
        for(var key in localStorage) {
            //All of the keys should point to user data except loggedInUser
            if(key !== "loggedInUser"){
                //Extract object containing user data

                //Extract user name and top score
                htmlStr += "David";
                //Add a table row to the HTML string.
            }
        }

        //Finish off the table
        htmlStr += "</table>";

        //Add the table to the page.

    }

</script>

2 个答案:

答案 0 :(得分:0)

要创建所需的输入字段,您应该

  • 将表单字段换成实际的<form>
  • 设置您的<button>是&#34;提交&#34;输入
  • onsubmit表单上触发您的功能,而不是在按钮的onclick事件
  • 上触发
  • 然后只需在HTML元素
  • 上设置required属性即可

实施例

<form onsubmit="registerUser()">
    <input type="text" name="username" value="" id="name" required>
    <input type="password" name="password" id="password" required>
    <button type="submit">Submit</button>
</form>

这是有效的,因为当提交表单时(通过真实的提交按钮),表单首先检查是否已满足所有字段验证器。如果未填写required字段,则表单将不会提交。因此,只有当表单完全有效时才会调用registerUser()函数,因为只有这样才会触发submit事件。

答案 1 :(得分:0)

只需将此行添加到您的代码中即可。 checkLogin()功能。它的作用是检查其中一个字段是否为空。如果为空,则将文本更改为&#34;请填写字段&#34;。即使大多数浏览器为您做到这一点,也不是以</ body>标签结尾的不良做法。

&#13;
&#13;
if(nameInput.length === 0 || pwdInput.length == 0)
{
    loginResult.innerHTML = "Please fill the fields.";
    return;
}
&#13;
&#13;
&#13;

这里我刚刚将该部分添加到您现有的代码中。

&#13;
&#13;
<html>
<head>
    <title>Week 9 Q&A Session - Form Demo</title>
</head>

<body>

    <!--Registration form -->
    <div>
        <h1>Registration</h1>
        <form onsubmit="registerUser()">
        <input type="text" name="username" value="" id="name" required>
        <input type="password" name="password" id="password" required>
        <button type="submit">Submit</button>
        </form>
    </div> 

    <!-- Login form -->
    <div>
        <h1>Login</h1>
        <input type="text" name="username" value="" id="loginName">
        <input type="password" name="password" id="loginPassword">
        <button onclick="checkLogin()">Submit</button>
        <p id="LoginResult">Not logged in.</p>
    </div> 

    <!-- Rankings table will be inserted here -->
    <div id="RankingsTable"></div>

    <script>

        /* Does some basic checking of user data then stores
        user data in localStorage */
        function registerUser(){
            //Extract the name and password that the user has entered
            var nameInput = document.getElementById("name").value;
            var pwdInput = document.getElementById("password").value; 

            //Check that the name and password are not empty
            if(nameInput !== "" && pwdInput !== ""){
                //Create a JavaScript object to hold the user data.
                var usrObj = {};

                //Add user entered data to object
                usrObj.username = nameInput;
                usrObj.password = pwdInput;

                //Add a score field to object to support rankings table
                usrObj.topscore = 0;

                //Store a string version of the object in local storage.
                localStorage[nameInput] = JSON.stringify(usrObj);
            }
        }


        /* Checks that the username and password match the user name and password of a 
        registered user and provides feedback to user. */
        function checkLogin(){
            //Get a reference to the div where we will display the login result
            var loginResult = document.getElementById("LoginResult");

            //Extract the name and password that the user has entered
            var nameInput = document.getElementById("loginName").value;
            var pwdInput = document.getElementById("loginPassword").value; 

            //Output for debugging
            console.log("Login name: " + nameInput+ "; Login password" + pwdInput);
            if(nameInput.length === 0 || pwdInput.length == 0)
            {
                loginResult.innerHTML = "Please fill the fields.";
                return;
            }
            //Check to see if we have data stored for this user
            if(localStorage[nameInput] === undefined){
                //No user found - provide feedback to user.
                loginResult.innerHTML = "User name incorrect";
                return;
            }

            //Check password
            //Get object that is stored for the user name.
            var usrObj = JSON.parse(localStorage[nameInput]);

            //Compare the entered password with the stored password
            if(pwdInput !== usrObj.password){
            //Incorrect password - provide feedback to user
            loginResult.innerHTML = "Password incorrect";
            return;
        }

        //If we have got this far, the username and password are correct

        //Record the user that has logged in using local storage.
        localStorage.loggedInUser = nameInput;

        //Provide feedback to user - you could also provide a logout button - see the example in my slides.
        loginResult.innerHTML = "User logged in.";
        }


        /* This function is called when a logged in user 
        plays the game and gets a score */
        function updateScore(newScore){
            //Get the JavaScript object that holds the data for the logged in user
            var usrObj = JSON.parse(localStorage[localStorage.loggedInUser]);

            //Update the user object with the new top score
            /* NOTE YOU NEED TO CHANGE THIS CODE TO CHECK TO SEE IF THE NEW SCORE
            IS GREATER THAN THE OLD SCORE */
            usrObj.topscore = newScore;

            //Put the user data back into local storage.
            localStorage[localStorage.loggedInUser] = JSON.stringify(usrObj);
        }


        /* Loads the rankings table.
        This function should be called when the page containing the rankings table loads */
        function showRankingsTable(){
            //Get a reference to the div that will hold the rankings table.
            var rankingDiv = document.getElementById("RankingsTable");

            //Create a variable that will hold the HTML for the rankings table
            var htmlStr = "";

            //Add a heading 
            htmlStr += "<h1>Rankings Table</h1>";

            //Add the table tag
            htmlStr += "<table>";

            //Work through all of the keys in local storage
            for(var key in localStorage) {
                //All of the keys should point to user data except loggedInUser
                if(key !== "loggedInUser"){
                //Extract object containing user data

                //Extract user name and top score
                htmlStr += "David";
                //Add a table row to the HTML string.
                }
            }

            //Finish off the table
            htmlStr += "</table>";

            //Add the table to the page.

        }

    </script>
    
</body>
&#13;
&#13;
&#13;