Problem to redirect with javascript (window.location.href)

Asked

Viewed 1,981 times

0

Hello, I wish users can only access a certain area of the site if they have an access password.

my code is this:

function redirect() {
  var pass;
  pass = prompt("Qual a palavra mágica?");
  if (pass == "asdfouch") {
    window.location.href = '[link]';
  } 
  else {
    alert("Ops, desculpe mas você ainda não tem acesso ou digitou o código errado :/");
  }
}

If I enter the wrong password I get the alert, but nothing happens when typing the correct password.

2 answers

0

The error is: unfinished string constant

That line

alert("Ops, desculpe mas você ainda não tem acesso ou digitou o código errado :/");

seems to be broken!

function redirect() {
  var pass;
  pass = prompt("Qual a palavra mágica?");
  if (pass == "asdfouch") {
    window.location.href = '/unanswered';
  } 
  else {
    alert("Ops, desculpe mas você ainda não tem acesso ou digitou o código errado :/");
  }
}
<button onclick="redirect()">Click me</button>

  • the line break was error at the time I was typing here on the site only (unfortunately it would have solved the problem hahah) .

  • @Felipeaugusto did not understand, "typing here on the site", you mean you were wrong in the formulation of the question and then the error is not this in its application? Which error still persists? On the run of my answer is working!

  • was only an error of formwork here on own site. In the program the line is not broken. Unfortunately the problem persists.

  • the function call in html is done like this: <form method="POST" onclick="redirect()"> <input type="Submit" value="I can enter?">

  • There’s the reason, you can do it like this: <input type="button" value="Posso entrar?" onclick="redirect()"> without the use of form

  • It worked by applying this change. obg!

  • 1

    @Felipeaugusto my answer was correct regardless of whether you told me you were using onclick in the form. If the onclick is on the button it could not be in the form evidently. In the next questions try to post the code as it is in your application, that is, try not to generate more errors in the post of your question to not give extra work without need to those who want to help you

Show 2 more comments

0


Beyond the window.location.href you can use window.location.replace

If you want to simulate someone by clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace

Source: How to redirect to another page? ( Stack in English )

function redirect() {
  var pass;
  pass = prompt("Qual a palavra mágica?");
  if (pass == "asdfouch") {
     window.location.replace("/unanswered");
  } 
  else {
    alert("Ops, desculpe mas você ainda não tem acesso ou digitou o código errado :/");
  }
}
<input type="button" value="Posso entrar?" onclick="redirect()">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.