创建一个“简单”密码验证字段 [英] Creating a "simple" password validation field
问题描述
我正在尝试为网页设置一个密码字段。到目前为止,我有:
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>
可怜我知道。它不一定是花哨的,我只是需要它从文本框中获取密码并将其与页面的密码进行匹配。我假设我可以使用if-else?
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.
推荐答案
,您需要将验证放在一个函数中,该函数在按钮的 onclick
事件中被调用。还要访问js中的< input
节点的密码,您可以给它一个 id
并使用的document.getElementById(ID)
。此外, =
是一个赋值运算符。使用 ==
进行比较:)
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>
或者更简单的方法是将密码DOM节点作为参数传递给函数:
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>
这篇关于创建一个“简单”密码验证字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!