4

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?

2 Answers 2

8

Try this instead.

$('#textBoxId').keydown(function(e) {
  if(e.keyCode === 13) {
    e.preventDefault(); 
    $('#buttonId').trigger('click');
  }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.