【问题标题】:Function that checks if User has inputted something检查用户是否输入内容的功能
【发布时间】:2018-05-29 09:22:39
【问题描述】:

我在如何添加功能时遇到了一些困难。有人可以告诉我如何添加一个功能,该功能将显示一条弹出消息“名称/密码字段为空” 这里的问题是如果我点击登录,而输入字段为空,它仍然说用户登录?即使他们是空的?我不能使用任何 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>

【问题讨论】:

  • 您可以在相应的红色文本下方显示错误消息,而不是弹出窗口。
  • 您还可以在输入标签中使用 html5 验证,例如“必需”
  • 我试过了,但它不起作用。你可以试试这个代码并告诉我它是否适合你吗?
  • 您尝试过什么,html5 验证?还要检查您的浏览器版本
  • 你能告诉我工作代码是什么样子的吗

标签: javascript function require required


【解决方案1】:

只需将此行添加到您的代码中。 checkLogin() 函数。它的作用是检查任何一个字段是否为空。如果它为空,则将文本更改为“请填写字段”。即使大多数浏览器都为您这样做,也不以 &lt;/ body&gt; 标记结尾也是不好的做法。

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

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

<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>

【讨论】:

    【解决方案2】:

    要使输入字段成为必填项,您应该

    • 将表单字段包装在实际的 &lt;form&gt;
    • 将您的&lt;button&gt; 设置为“提交”类型
    • 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 事件。

    【讨论】:

    • 你能把它应用到我的代码中吗?我刚试过,但它不适合我
    • @NatalieMcKnight 我有一个代码示例,根据您的代码在我的答案中演示它。
    • 我更新了我的代码,看看。它仍然不适合我:/
    • @NatalieMcKnight 您能否更具体地说明什么不起作用。
    • 好吧,我按照您告诉我的表格做了,但是如果您尝试我的代码,您会发现即使字段为空,它仍然显示“已登录”
    猜你喜欢
    • 2021-12-17
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 2021-03-25
    相关资源
    最近更新 更多