9

Trying to get my button to act like a link (tried the <A> tag and it would work if you open in a new tab but not if you click on it. Then tried this code and nothing. Suggestions?

<button onClick="location.href='/secure/edit.aspx?id=671'">Edit</button>
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Geekender
  • 799
  • 4
  • 9
  • 18

4 Answers4

15

You need to explicitly say window.location because this in the context of the button is the button object itself. Ordinarily, JavaScript is run in the context of the window object, so you don't need to do that.

<button onClick="javascript:window.location.href='/secure/edit.aspx?id=671'">Edit</button>

(Additionally, I also like to explicitly state that the script is javascript:, but that's purely a personal thing.)

Oliver Moran
  • 5,137
  • 4
  • 31
  • 45
  • 1
    The `javascript` label is useless. – RobG Sep 20 '12 at 23:03
  • Redundant, not useless. See https://gist.github.com/3770452 However, why I like to include it is because I believe it improves readability. – Oliver Moran Sep 23 '12 at 12:43
  • 1
    Depends on language. In US English, redundant is often used to mean "backup" or "failover" (e.g. a redundant system for emergency power). In other versions of English, redundant means unnecessary or surplus to requirements, so it's a synonym for useless. :-) – RobG Sep 23 '12 at 23:41
  • It's misleading. It doesn't specify the language, it provides a [place to break or continue to](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). – Quentin Jun 23 '15 at 09:59
  • @Quentin Jun, it actually does (or did?) in IE, see the example above or here: http://stackoverflow.com/questions/10068781/what-does-the-javascript-pseudo-protocol-actually-do ... but, I use it for readability. – Oliver Moran Aug 11 '15 at 08:53
7
<button onclick="window.location='/secure/edit.aspx?id=671'">Edit</button>
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
2

Try with window.location

<button onClick="window.location='/secure/edit.aspx?id=671'">Edit</button>
Tarsis Azevedo
  • 1,463
  • 14
  • 21
0

Add type = "button"

<button type = "button" onClick="window.location='/secure/edit.aspx?id=671'">Edit</button>

You need to add the type, otherwise the button will act as a submit button and will POST your form instead of redirecting to the desired url.

Nixon
  • 1,565
  • 1
  • 9
  • 2