0

I'm very new to coding. I apologize if this is a simple or insultingly basic question (this is my first time posting here). I have no idea why my javascript isn't working, and I don't know what resources to use to find out on my own, as it seems (to me) to be a sort of oddly specific situation.

Here's my code:

var correct = "password";                                   //Set "correct" to the correct password

  function isenter(){                                             
      var pressed = event.which;                                  
      if (pressed === 13){                                    //If key pressed is "Enter"
          var pwinput = document.getElementById("pw").value;  //Set "pwinput" to the value of the password input field (id="pw")
          window.alert(correct + " " + pwinput);              //Display values of correct and entered password (for debugging)
          if (pwinput === correct) {                          //If entered password is equal to correct password
              window.alert("Match registered");               //Display "Match Registered" (for debugging)
             window.location = "lobby.html";                 //Redirect to another page (THIS IS WHAT ISN'T WORKING)
         }
         else{
             window.alert("Match NOT registered")            //Display "Match NOT registered" (for debugging)
         }
     }
 }

 window.addEventListener("keypress", isenter)                //Listen for keypresses. Run isenter when keys are pressed

The page will not redirect(line 10). I can't think of why it won't. The line directly above it confirms that a match has been registered, and that that particular branch of code is in fact running, but line 10 does not work properly for some reason. If I ctrl-x line 10 and paste it between line 4 and 5, it works fine (redirecting to the new page whenever a key is pressed), telling me that it SHOULD work, but doesn't due to its location for some reason. The only thing I can think is that being inside the "if" statement is preventing it from working properly, but I don't know why this should be the case...

Any help would be much appreciated! Again, this is my first time posting here. sorry if I'm breaking any protocol or conventions or if my code is a wreck. Thank you in advance! I know I'm probably missing something stupid basic.

UPDATE:
I've noticed that when I change...

if (pwinput === correct) {

...to...

if (pwinput === "") {

...then the redirect is successful whenever I hit "Enter". It seems like the field NOT being empty is preventing the redirect somehow. I'm still not sure what's going on. I hope this added information helps!

UPDATE TWO:
After removing a pair of "form" tags from around the "pw" input, the code now works as expected. I'm currently trying to figure out how to get things working without removing the form tags.

On the suggestion of @tim, I've switched to using "onsubmit" with the form. This simplifies my code a bit, but I'm still running into the same problem. The code around the redirect is running, but the redirect itself isn't working. Here's a barebones html sample with the javascript embedded. I have a form, a button, and a link. The link and the button work fine, but the form still won't redirect.

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
    <title>First Page</title>
</head>
<body>
    <form id="pwform" name="myform">
        <input id="pw" type="password">
    </form>
    <button id="btn">run test function</button>
    <a href="newpage.html">link to next page</a>
<script type="text/javascript">
    function testfunction(){
        window.alert("Test function ran.");   //Verify that testfunction is running.
        window.location ="newpage.html";      //Redirect (works on button, not on form)
    }



    document.getElementById("pwform").onsubmit = testfunction;    // <-- I don't know what the
    document.getElementById("btn").onclick = testfunction;        // <-- difference between these is.
</script>
</body>
</html>

I'm confused, because I don't think I have any reason to expect a difference in the code being run from the button and that being run from the submission of the form. The alert pops up when submitting the form, confirming that the code is running, but the redirect itself isn't working.

Is there syntax or something I'm not following?

ADDENDUM:
I know this isn't the "right" way to do a password. I'm just getting practice on some of the basics.

Josh
  • 3
  • 3
  • try window.location.href = "lobby.html"; – HaukurHaf Oct 10 '18 at 22:43
  • @haukurHaf that doesnt matter – Jonas Wilms Oct 10 '18 at 22:45
  • I just tried your code and it does work fine, at least in Chrome. Try this fiddle here: https://jsfiddle.net/pdvm2xLq/ It tries to go to lobby.html but since that file obviously does not exist, a 404 page is shown. The location change/redirect is being done. – HaukurHaf Oct 10 '18 at 22:51
  • Thanks for the fiddle. I'll mess around with it. I don't know why it's behaving differently there than it is for me locally. It could be something in another of my files. – Josh Oct 10 '18 at 22:56
  • What browser are you using? Does the lobby.html file exist in the same location as the file which hosts this code? – HaukurHaf Oct 10 '18 at 23:00
  • I'm using Chrome. Yes, the file (index.html) hosting this code shares a folder with lobby.html. – Josh Oct 10 '18 at 23:06
  • Are there any errors in the console? – Barmar Oct 10 '18 at 23:52
  • @Barmar there are no errors in the console. – Josh Oct 11 '18 at 00:46
  • Are you getting the alert before the location change? – Barmar Oct 11 '18 at 00:48
  • I don't know if I understand your question. There is no location change happening. I get both of the "correct+pwinput" and the "Match registered" alerts, but nothing happens after I click through those alerts. But yeah, the alerts come before the change in the code, if that's what you meant. – Josh Oct 11 '18 at 01:01

2 Answers2

0

I always use window.location.replace("relative path to link"); because it works on Google Chrome, Firefox, and Microsoft Edge! But since that isn't working for you, try document.location.assign("link"); and document.location.replace("link");.

Sources:

Location.Assign

Location.Replace

Now I know that this wasn't part of the question, but according to Mozilla Docs for JavaScript, the best way to control key codes is not event.which, but it is actually event.key. Here is a list of Key Codes that you can use for if (event.key === "a"), and here is how to use event.key

I answered a question about this earlier: here

Instead of going through all of this hassle with keypress why don't you just use a form? Any button click, or enter press will automatically trigger a submit, and it is more Mobile-Friendly. All you have to do is stop the rerouting with javascript:void(0); and use the onsubmit event to trigger your function.

<form action="javascript:void(0);" onsubmit="login()">
    <table>
        <tr>
            <td>Username:</td>
            <td><input type="text" placeholder="Username..." /></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password": placeholder="Password..." /></td>
        </tr>
        <tr><td colspan="2"><button>Submit</button></td></tr>
    </table>
</form>
<script>
    function login() {
        //Login Code Here
    }
</script>
Da Mahdi03
  • 1,468
  • 1
  • 9
  • 18
  • Unfortunately I still encounter the same problems when I change the format of that particular line. – Josh Oct 11 '18 at 01:37
  • Thank you for this information though! Every scrap of knowledge I can gather is valuable to me in this stage of my learning. – Josh Oct 11 '18 at 01:49
  • I've found a version that works after stripping out all the css and most of the irrelevant html. I'm currently piecing it back together to see what works and what doesn't. No solution yet, but I'm not as utterly lost as I was before. – Josh Oct 11 '18 at 02:44
  • @Josh That's great!! – Da Mahdi03 Oct 11 '18 at 02:45
0

You need to pass event to your function parameter. I checked it out on the plunker linked to above and that seemed to be your problem. You just need to change function isenter() { ... } to function isenter(event) { ... } since you're attempting to use event.which inside your function. Here's the forked fiddle: https://jsfiddle.net/ot7863xe/

 function isenter(event){ // <--------------- add event here                                            
          var pressed = event.which;                                  
          if (pressed === 13){                                    //If key pressed is "Enter"
              var pwinput = document.getElementById("pw").value;  //Set "pwinput" to the value of the password input field (id="pw")
              window.alert(correct + " " + pwinput);              //Display values of correct and entered password (for debugging)
              if (pwinput === correct) {                          //If entered password is equal to correct password
                  window.alert("Match registered");               //Display "Match Registered" (for debugging)
                 window.location = "lobby.html";                 //Redirect to another page (THIS IS WHAT ISN'T WORKING)
             }
             else{
                 window.alert("Match NOT registered")            //Display "Match NOT registered" (for debugging)
             }
         }
     }

Update based on answer

You shouldn't need to remove your form tags to get it to work. If you attach the onsubmit handler to a form, you can register a function that you've written to execute a function when the form is submitted. In that way, you can also eliminate the code you've written to track whether the user has pressed "enter" and you also can get rid of the window.addEventListener so that you're not tracking every key press. See the jsFiddle here: https://jsfiddle.net/ot7863xe/

I made it so that a form uses the onsubmit handler and your function executes when the user presses Enter.

Update 2 to allow for redirect in form

You have to add action="newpage.html" in your form element so that the form knows where to go. Your isenter function and testFunction in your most recent update should handle the logic necessary to return true or false so that the form will either redirect or not. If you function returns true then the form will look at the action inline and go to that page. On the other hand, if your function returns false, the form will be prevented from submitting (and will not redirect).

Therefore, notice below that I added the action to your form tag and just made your testFunction return true so that the redirect will occur on form submit. If you change the return value to false nothing will happen.

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
    <title>First Page</title>
</head>
<body>
    <form id="pwform" name="myform" action="newpage.html" onsubmit="testfunction()">
        <input id="pw" type="password">
        <button type="submit" id="btn">run test function</button>
    </form>

<script type="text/javascript">
    function testfunction(){
        window.alert("Test function ran.");   //Verify that testfunction is running.
        //window.location.replace("newpage.html");      //Redirect (works on button, not on form)
        return true;
    }



    document.getElementById("pwform").onsubmit = testfunction;    // <-- I don't know what the --> it attaches handler to the form (which you don't need to do - you can just specify that inline in the form like above)
    //document.getElementById("btn").onclick = testfunction;        // <-- difference between these is --> it adds a click handler directly to the button element (not the form).
</script>
</body>
</html>
tlm
  • 952
  • 10
  • 20
  • Thanks for the tip! I was able to simplify things using onsubmit, but I'm still running into issues. Check my second update. – Josh Oct 11 '18 at 18:05
  • @Josh see my updated answer. It should now submit and redirect you. – tlm Oct 11 '18 at 18:51