问题
I am trying to set a password to a form. I basically want someone to type a password into a password field and hit submit and if the password is right, it redirects them to buybutton.php in the same window. If the password isn't right, a javascript alert pops up that says 'Password wrong'. I've tried to write out the Javascript but no action is happening when the button is clicked. What have I done wrong in my code below? Thanks for the help!
<!DOCTYPE html>
<body width="950" height="300" style="background-image:url('giftcard_bg.jpg');">
<head>
<SCRIPT LANGUAGE="JavaScript">
function goForit() {
var passwd;
passwd = this.document.giftForm.pass.value;
if(passwd=="samsamsam"){
window.open ('buybutton.php','_self',false)
}
else{
alert('Password wrong');
}
}
</SCRIPT>
</head>
<div style="position:absolute; top:150px; left:285px; text-align:center;">
<form id="giftForm">
<input type="password" id="pass" placeholder="Enter Secret Code" style="font-size:150%;"/>
<br />
<input type="button" onClick="goForit()" value="Submit" style="font-size:150%; margin-top:15px;" />
</form>
</div>
</body>
</html>
回答1:
passwd = this.document.giftForm.pass.value;
causes an error try
passwd = document.getElementById('pass').value;
You were missing a ;
too after window.open ('buybutton.php','_self',false)
回答2:
You should use document.getElementById('pass').value
instead of this.document.giftForm.pass.value
function goForit() {
var passwd;
passwd = document.getElementById('pass').value;
if(passwd=="samsamsam"){
window.open ('buybutton.php','_self',false)
}
else{
alert('Password wrong');
}
}
Word of warning:
But be aware! Everybody can see the source code and find the password!!!
Instead of this, you should send the form to the server, and in the server side, check if it's correct. If it's correct, redirect the user to buybutton.php, but sending him a cookie which authorises him to enter to that page. And that page should check if he has that cookie.
But I'm not an expert, if you want that you should make another question asking that.
回答3:
this should work
function goForit() {
var passwd = document.getElementById("pass").value;
if(passwd=="samsamsam"){
window.open ('buybutton.php','_self',false)
}
else{
alert('Password wrong');
}
}
回答4:
Oriol and Rajeev's answer are correct.
Alternatively, you can do this:
change
passwd = this.document.giftForm.pass.value;
to
passwd = document.forms['giftForm'].pass.value;
来源:https://stackoverflow.com/questions/11992332/javascript-password-submit-form