开发者

How to handle enter key in Javascript overlay?

开发者 https://www.devze.com 2023-01-23 00:35 出处:网络
I have a JavaScript overlay that consists of several input text search criteria. When the user presses the enter key in any of those inputs, I want to mimic the behaviour of the search button.

I have a JavaScript overlay that consists of several input text search criteria. When the user presses the enter key in any of those inputs, I want to mimic the behaviour of the search button.

I know how to handle the enter key if there is only one input. I define the input as:

<input type=\"text\" class=\"txtOrgNmFilter inputBox\" onkeyup=\"ClientsListControl.onFilterKeyup(event);\" /开发者_高级运维>

and in the onFilterKey up

onFilterKeyup: function(event) {
    if (event.keyCode == 13) {
        $(".txtOrgNmFilter").click();
    }
}

My question is as follows: if I have several input texts, do I need to add the onKeyUp attribute in all of them or is there a simpler way (similar to a form submit action)?

My overlay is a table


$('input').bind('keypress',function (event){
  if (event.keyCode === 13){
    $(this).trigger('click');
  }
});

With this you can bind the same event to all inputs (you can filter more if you want) and when someone clicks 'enter' with the focus on some this inputs, it will trigger the 'click' event.


Attach the event handler to the container (the table). Then you can get the element that the key was actually pressed in (in prototype.js, use Event.findElement, but I'm sure other libraries have similar methods) and make one lot of logic depend on both that and the key pressed.


Can't you just include a form element, in which you define your inputs? This way, the browser will by default submit the form when a user presses Enter in one of the input fields.

And if you want to handle the search by yourself (e.g., using AJAX), you can catch the submit event of the form and perform the desired action. Doing so your form will still work if JavaScript is unavailable one way or another.

0

精彩评论

暂无评论...
验证码 换一张
取 消