tags:

views:

42

answers:

4

Hi all

In the example code below I have a button that when clicked reloads the page, but hitting enter does not do so, how would one amend it so that hitting enter would also refresh the page

<h3>click to refresh page</h3>
<input type="button" value="Refresh" onClick="history.go(0)">

Thank You Ruth

A: 

You need to set the focus. In your onload function:

var button = document.getElementById("mybutton"); 
button.focus(); 

You could also add an on key press event:

http://help.dottoro.com/ljlwfxum.php

http://www.devguru.com/Technologies/ecmascript/quickref/evhan_onkeypress.html

Kevin
A: 

You can do it like this:

<h3>click to refresh page</h3>
<form onSubmit="history.go(0); return false;">
<input type="submit" value="Search"></form>
puckipedia
I couldn't get this method to work for me in Firefox 3.6
Mr. Shiny and New
Thinking wrong :(
puckipedia
+1  A: 

You could set a key handler on the page itself if you want to catch any ENTER keypress anywhere:

function catchCR(e) {
  if (!e) {
    e = window.event; // for IE
  }
  var key = 0;
  if (e.keyCode) { key = e.keyCode; } // IE
  if (e.which) { key = e.which; } // FF

  if (key == 13 /* enter key */) {
    history.go(0);
  }
}
if (document.addEventListener) {
  document.addEventListener("keydown", catchCR, true);
} else if (document.attachEvent) {
  document.attachEvent("onkeydown",catchCR);
}
Mr. Shiny and New
A: 

You could do by setting an event on the document.

Try this:

//Traditional Way
document.onkeypress = function(event){
    event = event || window.event;
    key=event.keyCode;
    if (key == "13") //Enter
    {
         history.go(0);
    }
};

//OR

function keyHandler(event){
    event = event || window.event;
    key=event.keyCode;
    if (key == "13") //Enter
    {
         history.go(0);
    }

}
//Modern W3c Way
if (document.addEventListener) {
  document.addEventListener("keydown", keyHandler, false);
}
//IE Way 
else if (document.attachEvent) {
  document.attachEvent("onkeydown",keyHandler);
}
It looks like you are building a Rube Goldberg machine... don't click a button from Javascript! Invoke your desired behaviour directly please.
Mr. Shiny and New
@Mr. Shiny and New. Ok calm down! I'm used to doing that for other operations. But I suppose its not needed here.