views:

1013

answers:

2

I have a ASP.NET page which has a form on it. It also has a search form on it. The search is in the top-right of the page, so the button for the search is the first added to the control hierachy.

When you're working on the other form and press enter it will click on the search button. I don't want this, I would prefer that when you press enter the button for the form is clicked.

I tried using jQuery like this:

$('#textBoxId').keyup(function(e) {
  if(e.keyCode === 13) { 
    $('#buttonId').click();
    e.preventDefault();
  }
});

But the form submitted, meaning that the client-side validation didn't run (ie, the onclick event handler wasn't run on the button).

What's the best way to achieve this?

+4  A: 

Try this instead.

$('#textBoxId').keydown(function(e) {
  if(e.keyCode === 13) {
    e.preventDefault(); 
    $('#buttonId').trigger('click');
  }
});
tvanfosson
trigger is sweet, thanks
Slace
Exactly what I was looking for... thanks!
Elijah Manor
A: 

This code works in IE and FF:

$('#textBoxId').keydown(function(event) {
    var e = event || window.event;
    var keyCode = document.all ? e.keyCode : e.which;

    if (keyCode == 13) {
        e.preventDefault();
        $('#buttonId')[0].click();
    }
});

The important thing to remember is that the jQuery call to click() only calls all handlers that are bound to the click event. It does not call the underlying html object's click() method. This has to be done manually by extracting the elements from the jQuery array as per the last line in the if statement.

Lette