views:

34

answers:

3

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

A: 

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.

Colin Fine
THanks I am gongi to try to use your method.
Dadou
Sorry not to have answered earlier, I had to go out yesterday. I am not sure what you mean by "Attach the event handler to the table"?. THanks
Dadou
+1  A: 
$('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.

madeinstefano
THanks, I will try it
Dadou
I tried and it works great. THanks
Dadou
A: 

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.

Marcel Korpel
I tried that method but I cannot add a form becasue the overlay is already inside a form.
Dadou
@user: But can't you add an `onsubmit` handler to the current form?
Marcel Korpel
THe current form has already a on submit for the "main" Page, but I want to do handle the enter key for the overlay. THe "main" has several overlays, so I would have to know which one isa showing and it would be quite complicated ( I think).
Dadou