user1935067
user1935067

Reputation:

How to compare form elements with strings in an if statment

I'm having allot of trouble with this and I've tried many different ways to do this and I just ran out of ideas.

Here's my code:

var user = document.Log.User;
var pass = document.Log.Pass;

function Login (){
if(user.value == "Admin"){
window.open();
}
}

Here Is the HTML side:

<form name="Log">
        <input class="Log" type="text" name="User">
    <input class="Log" type="password" name="Pass">
    <input type="button" value="Login" name="But" onclick="Login()" style="width: 70px;position: relative;left: 150px;top: -25px;">
</form>

Upvotes: 1

Views: 119

Answers (3)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18354

I don't know why you are doing this kind of login logic stuff with js, but, this would work:

function Login (){
  var user = document.querySelector('form[name=Log] [name=User]');
  var pass = document.querySelector('form[name=Log] [name=Pass]');

  if(user.value == "Admin"){
     window.open("yoururl.com");
  }
}

Hope this helps. Cheers

Upvotes: 0

Mohammad Masoudian
Mohammad Masoudian

Reputation: 3501

use id Selector an put your variable assignments inside Login function:

HTML :

<form name="Log">
    <input id="User" class="Log" type="text" name="User">
    <input id="Pass" class="Log" type="password" name="Pass">
    <input type="button" value="Login" name="But" onclick="Login()" style="width: 70px;position: relative;left: 150px;top: -25px;">
</form>

JS:

function Login (){
    var user = document.getElementById("User");
    var pass = document.getElementById("Pass");

    if(user.value == "Admin"){
        window.open();
    }
}

Upvotes: 1

Barmar
Barmar

Reputation: 781210

If your variable assignments are in Javascript that's loaded before the body, then the elements that they refer to don't exist yet, and you should be getting errors. There are a number of ways to fix this:

  1. Put the Javascript in the body somewhere after the form.
  2. Put the Javascript inside window.onload=function() { ... }.
  3. Assign the variables inside the Login() function.

Upvotes: 1

Related Questions