Javascript Password Submit - Form

◇◆丶佛笑我妖孽 提交于 2019-12-12 04:59:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!