2

I can't figure out why my code doesn't validate my input value. I get "not working" for all scenarios.

This is my code:

<body>


<input type="text" placeholder="User Name" id="id_inputuser"/>
<label>Enter User Name</label><br>
<input type="text" placeholder="Password"id="id_inputpass"/>
<label>Enter Password</label><br><br>

<button onClick="verify()">Enter</button>
</body>

Javascript:

var user = document.querySelector('#id_inputuser').value;

function verify()

{if (user == "david")
{alert("working");}

else{alert("not working")};
}

Can someone help?

Thanks a lot!

2
  • Can you list your scenarios? If the input is not "david" it will fail... what is the desired behavior? Commented Dec 2, 2015 at 19:22
  • when i input "david" it still writes "not working" Commented Dec 2, 2015 at 19:25

2 Answers 2

2

You have to read the input value inside the function.

function verify(){
    var user = document.querySelector('#id_inputuser').value;
    if (user == "david"){
        alert("working");
    }
    else{
        alert("not working");
   }
}

If you let that sentence out of the function, it is executed when the page is loaded, and in that moment, the input has not value.

Sign up to request clarification or add additional context in comments.

4 Comments

Whenn i put the var inside the function, i get an error: Unexpected token var. Do you know why?
Yes, you have a typo with some parenthesis or braces. Check it all. In you original code, for example, in the else sentence, you had the alert semicolon out of the closing brace.
If you don't have copied my code but used yours, maybe you have written that sentence before the opening brace of the function (between "verify()" and "{if"). That would cause the error.
You were right, it was a brackets mistake. Thanks a lot!
0

Your call to querySelector gets the value when the field is empty, that means when the DOM is ready, and not after you've changed the input field. You need to catch the value when you call the function you've provided.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.