views:

25

answers:

2

I have a textbox and a button ,the button click event navigates to other location in the website i want to do the same thing on pressing enter key but unable to do that please helpme solve this my code snippet follows

function call() 
{
    document.location= "location.aspx";
} 

<input type="text" id="txt1" onkeydown ="if(event.keyCode==13)document.getElementById('bt1').click()"/>
<input type="button"  id="bt1" value ="Hit me" onclick ="call()" />
A: 

This is the same as the click, both would call this function...

onkeydown ="if(event.keyCode==13) call()"
BrunoLM
not a good idea: what if there are other handlers attached??
Andreas Niedermair
In this case it doesn't seem to have other handlers, he is setting the event through attributes.
BrunoLM
i believe this is a theoretical excerpt, not his fully working page :)
Andreas Niedermair
A: 

If you can edit your HTML code, you wont probably need to do any JS to get this to working. The INPUT fields in your HTML should be wrapped inside a FORM tag (atleast thats how it semantically makes more sense in most of the cases).

If you can do that, you can then change the INPUT element from TYPE button to Type SUBMIT and can then listen for the onsubmit event on your FORM element.

The event is fired both on pressing of enter key and click of the button and it works pretty smoothly across the browsers. The only problem is IE which doesnt fire the onsubmit event on a form with just 1 text input field. For that, you will have to insert another field into the form. You can hide it for your case. More ref at : http://style-vs-substance.com/development/form-submit-by-enter-key-and-internet-explorer/

EDIT: Code Sample

<form id="myForm">
    <!--[if IE]>
    <input type="text" style="display: none;" disabled="disabled" size="1" /><![endif]-->
    <input type="text"/>
    <input type="submit" value="Search"/>
</form>

Then in your JS:

var formHandler = document.getElementById('myForm');
formHandler.onsubmit = function(){
  //this callback will be invoked both by the search button and enter key now
  //your logic here
}
Rajat

related questions