HTML and JavaScript not working correcty

I just started learning javascript and I have been on HTML for some time now. I know I have successfully coded a right JavaScript code for my log in form.

Here is my JavaScript code:


<script>
function login(){
    var username=document.getElementById('usrnm');
    var password=document.getElementById('pass');
    if(username=="abc"){
        if(password=="123"){
            window.location.href="mypage.html"
        }
        else{
            window.location.href="error.html"
        }
    else{
        window.location.href="error.html"
    }
}
</script>

And here is my HTML form:


<form name="input" method="get">
<b>Username:</b>
<br>
<input id="usrnm" type="text" name="usrnm">
<br>
<br>
<b>Password:</b>
<br>
<input id="pass" type="password" name="pswrd">
<br>
<br>
<center>
<input id="login" type="image" src="login.png" value="login" onclick="login()">

When I click on the Log in button. It only reloads the same page it is in but as you can see, I intended to call "mypage.html". I'mm just starting to learn JavaScript so if there are any obvious reasons why my code wont work, be easy. Thanks =). I know my JavaScript works because when I tried inserting onclick="login()" to the line <form name="input" method="get"> the code directs me to "error.html" when I type on the Username field or Password field.

Upvotes: -1

Views: 131

Answers (4)

Surya Prakash Tumma
Surya Prakash Tumma

Reputation: 2193

change the code

var username=document.getElementById('usrnm').value;

var password=document.getElementById('pass').value;

Upvotes: 0

Naveen Kumar Alone
Naveen Kumar Alone

Reputation: 7668

Get the usrnm id, pass id values as

var username=document.getElementById('usrnm').value;
var password=document.getElementById('pass').value;

OR

Otherwise pass if condition as

if(username.value == "abc"){
    if(password.value == "123"){
      .....
    }
}

Upvotes: 0

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

You JS does not work as intended. You are selecting elements, but not their values. Try changing to the following:

<script>
function login(){
    var username=document.getElementById('usrnm').value;
    var password=document.getElementById('pass').value;
    if(username=="abc"){
        if(password=="123"){
            window.location.href="mypage.html"
        }
        else{
            window.location.href="error.html"
        }
    }
    else{
        window.location.href="error.html"
    }
}
</script>

Upvotes: 4

imulsion
imulsion

Reputation: 9040

You are not getting the element values, just the elements. Add .value to the end of your document.getElementById(id) method calls.

Upvotes: 4

Related Questions