Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the page's URL when a visitor clicks a button?

When a visitor clicks a button element, how can I change the URL?

Example:

<form id="search">
  <input type="text" />
  <button onclick="javascript:alert('hi');">Alert Hi</button>
  <button onclick="javascript:window.location.href='http://www.google.com/'">Go to Google</button>
</form>

(Or see JSFiddle.)

For a quick demo page, I just need to send the visitor to a new URL when they click a button. I can execute JavaScript onclick (in the Alert Hi button), and the URL changes if I execute window.location.href='http://www.google.com/' from Firebug's console. What do I need to do to change the URL on a button click?

like image 495
KatieK Avatar asked Nov 16 '12 23:11

KatieK


People also ask

How do I change the click on a HTML page?

By using HTML Anchor Tags <a>.. </a>, you can Redirect on a Single Button Click [html button click redirect]. To use HTML Anchor tags to redirect your User to Another page, you need to write your HTML Button between these HTML Anchor Tag's starting <a> and Closing </a> Tags.

How do you open a link that clicks a button?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.

Can a button have an href?

You'd intuitively expect to be able to use <button href="https://google.com"> analogous with the <a> element, but unfortunately no, this attribute does not exist according to HTML specification.


1 Answers

The problem is that the form is being submitted when you click on the button. Add type="button" so it doesn't submit the form. You also don't need javascript in the onclick attribute. See How to prevent buttons from submitting forms

Example http://jsfiddle.net/E7UEe/1/ Notice that it won't go to google.com because jsfiddle has disallowed it. Notice the error message Refused to display document because display forbidden by X-Frame-Options.

<form id="search">
  <input type="text" />
  <button onclick="javascript:alert('hi');">Alert Hi</button>
  <button type="button" onclick="window.location.href='http://www.google.com/'">Go to Google</button>
</form>​

An alternative that works without JS is the appearance:button CSS directive http://jsfiddle.net/d6gWA/

<a class="btn"> Link looking like button</a>​
.btn {
    appearance: button;
    -moz-appearance: button;
    -webkit-appearance: button;
    -ms-appearance: button;
}​

Or you could always put the button in a link http://jsfiddle.net/d6gWA/2/

<a class="btn" href="http://www.google.com" target="_blank"><button type="button">Link Button</button></a>​
like image 56
Juan Mendes Avatar answered Oct 31 '22 14:10

Juan Mendes