Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  62] [ 5]  / answers: 1 / hits: 30351  / 13 Years ago, tue, november 1, 2011, 12:00:00

I'm trying to make a password field for a webpage. So far I have:



<form name=PasswordField action=>
Password:
<input type=password name=password>
<input type=button value=Log in>
</form>


Pathetic I know. It doesn't have to be fancy, I just need it to get the password from the textbox and match it against the password for the page. I'm assuming I can use an if-else?



*Code for get password from textbox when the Log in button is pressed here*
if (password = rawr)
{alert('Correct!')}
else
{alert('Wrong Password')}


Sadly I've been fooling with this for hours. I tried functions, too, and that didn't seem to work (for me) either.


More From » forms

 Answers
72

If you go that route, you need to put the validation inside a function that gets called in the onclick event of your button. Also to access the password <input node in js, you can give it an id and use document.getElementById(id). Also, = is an assignment operator. Use == for comparison :)



<head>
<script type=text/javascript>
function isValid(){
var password = document.getElementById('password').value;
if (password == rawr)
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>

<form name=PasswordField action=>
Password:
<input type=password id=password name=password>
<input type=button value=Log in onclick=isValid();>
</form>


Or an even easier way would be to pass the password DOM node as an argument to the function:



<head>
<script type=text/javascript>
function isValid(myNode){
var password = myNode.value;
if (password == rawr)
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>

<form name=PasswordField action=>
Password:
<input type=password id=password name=password>
<input type=button value=Log in onclick=isValid(this);>
</form>

[#89341] Monday, October 31, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleyv

Total Points: 259
Total Questions: 99
Total Answers: 107

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;