Jquery – ASP.NET AJAX postback and jQuery

ajaxasp.netjquerypostback

I have a Textbox, a LinkButton and a RadioButtonList inside an UpdatePanel. When the button is clicked, the UpdatePanel shows matching items in the radiobuttonlist.

This works fine, but I now need to make the same happen OnKeyDown on the TextBox. I'm trying to cancel all AJAX requests in progress but not having much luck. Firstly, on every keypress the UpdatePanel posts back, so only one letter can be changed at a time. Secondly, the textbox loses focus on postback.

I need to show the list as normal, but OnKeyDown as well as when the button is pressed. This is what I have (control IDs shortened)

$('#textBoxId').live('keydown', function(e) { 
  if((e.keyCode >= 47 && e.keyCode <= 90) || e.keyCode == 13) {
    Sys.WebForms.PageRequestManager.getInstance().abortPostBack();
    $('#buttonId').click();
    $('#textBoxId').focus();
  }
});

Thanks for any insight.

Best Answer

First step would probably be to move the TextBox outside of the UpdatePanel (and use RegisterAsyncPostbackControl), which should solve the focus problem.

To solve the problem of postbacks on every keypress, what I've done in the past is trigger a timer to check the control for changes every X milliseconds instead of on every change. The process flow would look something like this:

  1. TextBox's onchange event is triggered
  2. UpdatePanel is updated
  3. TextBox's onchange event is cleared, timer is set to check for value change in X milliseconds
  4. If value changed again, UpdatePanel is updated, timer is reset to check again in X milliseconds
  5. If value did not change, TextBox's onchange event is reset to go back to step #1

This way you have more control over how often the panel gets updated.