Asteria
Asteria

Reputation: 330

Javascript: Redirect page onclick

I'm fiddling around with a pretend "Logon screen" but am having trouble when it comes to redirecting the page.

I've tried a couple of different suggestions that I've found on the site, but so far nothing has worked.

I honestly think I'm just doing it wrong.

Any advice?

HTML

<div class="title"><h1>Webby Site</h1></div>
<div class="login-page">
  <div class="form">
    <form class="login-form">
      <input id="User" type="text" placeholder="username"/>
      <input id="PWord" type="password" placeholder="password"/>
      <button class="button">Login</button>
      <p class="message">Not registered? <a>Create an account</a></p>
    </form>
  </div>
</div>

JS

$(document).ready(function(){
       $('.button').click(function(){
            if ($('input#User').val() === "1" && $('input#PWord').val() === "1"){
            document.location.href = "www.yoursite.com";
            } else {
                alert('Incorrect Account Details');
            }
        });
    });

Code I've tried (in the same area as document.location.href)

  1. document.location
  2. window.location
  3. window.location.href
  4. location.href

Upvotes: 0

Views: 17361

Answers (2)

user13522008
user13522008

Reputation:

For HTML, you can use <button onclick="location.href='url'">text</button>

You can also use <button onclick="window.location.replace(url)">text</button>

Upvotes: 0

Denis Sheremet
Denis Sheremet

Reputation: 2583

By default, button acts like input type="submit", so it's trying to submit your form. Use event.preventDefault() to avoid this behaviour.

Correct way to redirect is setting window.location.href.

Also, I strongly recommend not to try client-side authentification, because anyone could just read login and password in your js file.

Upvotes: 4

Related Questions