user5096599
user5096599

Reputation:

if statement is not returning expected result

If the user enters the string 'secret' in the password field, it should display the text in the last else statement. It is only returning the statement in the first else. Can someone explain why?

var pword = document.getElementById('password'); //create event listener on password field's blur event
pword.addEventListener('blur', passwordCheck, false);
var messageField = document.createElement('div');
messageField.setAttribute('id', 'forMessage');
var fieldPassword = document.getElementById('password');
//get form id to create parentNode for message field
var form = document.getElementById('form');
//append form to add message field div
form.appendChild(messageField);
//add message to messageField
var paragraph = document.createElement('p');
function passwordCheck(){ //check to make sure the password is equal to the string "secret"
    if (fieldPassword !=='secret'){
       var wrongPassword = document.createTextNode('That is not the right password');
       paragraph.appendChild(wrongPassword);
       messageField.appendChild(paragraph);
    }else{
        var correctPassword = document.createTextNode('Good... That is the right password');
        paragraph.appendChild(correctPassword);
        messageField.appendChild(paragraph);
        console.log('made it');
    }
}

Upvotes: 0

Views: 45

Answers (2)

Igwe Kalu
Igwe Kalu

Reputation: 14868

Look what you did:

  1. var pword = document.getElementById('password');

then again

  1. var fieldPassword = document.getElementById('password');

Why? - pword and fieldPassword are same objects.

Anyway, to the point. The expression fieldPassword !== 'secret' will always be true because fieldPassword is a DOM element, and not a string.

If you had something like <input type="password" id="password">, then you could get the clear password text from the value property of the input element.

What you probably want to do is in the line of if(fieldPassword.value !== 'secret')

Upvotes: 0

CD..
CD..

Reputation: 74096

fieldPassword is the input element, not the value, so try:

fieldPassword.value !== 'secret'

Instead of:

fieldPassword !== 'secret'

Upvotes: 1

Related Questions