Raja Shekar Raja Shekar - 1 year ago 85
HTML Question

Json Login with multiple user credentials

I am trying to do a login form by using JSON, below is my code:

<title> Login Form</title>
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var Userlist = [{"username":"asdf", "password":"123"}, {"username":"zxc", "password":"123"}]
var jobj = JSON.parse(Userlist);
for (var i=0; i < jobj.length; i++) {
if ( username == jobj.username && password == jobj.password)
alert ("Login successfully");
alert("Invalid username and password");

<div class="container">
<div class="main">
<h2>Login Form</h2>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" placeholder="Enter username" name="username" id="username"/>
<label>Password :</label>
<input type="password" placeholder="Enter Password" name="password" id="password"/>
<input type="button" value="Login" id="submit" onclick="validate()"/>

I am unable to achieve this, when I enter with the given credentials nothing is appearing on the screen, Do I have to add some more functionality to achieve?

Answer Source

Working example

You don't need :

var jobj = JSON.parse(Userlist);

Just parse array like :

for (var i=0; i < Userlist.length; i++) {    
    if ( username == Userlist[i].username && password == Userlist[i].password)
        alert ("Login successfully");
        alert("Invalid username and password");

NOTE: add break; in case of correct informations to stop parsing the rest of objects.

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download