简体   繁体   中英

Check if username already exists, no ajax or php, just pure js

Here is the code:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript"> 
        function submit() 
        {
            var ul = document.getElementById("names");
            var name = document.getElementById("name").value;

            var i = 0, flag = 0;
            var allNames = [];
            if (allNames.length == 0) 
            {
                allNames[0] = name;
            }
            else 
            {
                if (allNames.includes(name))
                {
                    alert("Name already exists.");
                    return -1;
                }
                else 
                {
                    allNames[i++] = name;
                }
            }
            var li = document.createElement("li");
            li.innerHTML = name;

            ul.appendChild(li);
            document.getElementById("name").value = "";
        }
    </script>
</head>
<body>
    <input type="text" id="name">
    <button onclick="submit()">Submit</button>
    <div>
        <h2>Usernames</h2>
        <ul id="names"></ul>
    </div>
</body>
</html>

Is there any way to check if a username already exists and therefore block the new entry, only using javascript?

I've tried also moving the initialization of the array outside of the function but it doesn't work that way either...

Yes, just declare the allNames variable outside of your function. You currently create it with an empty array each time you call the submit function.

You also have an issue because your i is set to 0 every time. Just use .push if it is not included ( instead of trying to specify the index ).

 var allNames = []; function submit() { var ul = document.getElementById("names"); var name = document.getElementById("name").value; if (allNames.includes(name)) { alert("Name already exists."); return -1; } else { allNames.push(name); } var li = document.createElement("li"); li.innerHTML = name; ul.appendChild(li); document.getElementById("name").value = ""; }
 <input type="text" id="name"> <button onclick="submit()">Submit</button> <div> <h2>Usernames</h2> <ul id="names"></ul> </div>

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