views:

939

answers:

4

I have gone insane trying to figure out how to make this work. Code looks roughly like:

function onDropDownChanged() {
  $("#updatePanel").load(
    "myUrl",
    { id: $("#myDropDown option:selected").val() },
    onPanelLoaded
  );
}
function onPanelLoaded() {
  $("#theTextInput").focus();
}
$(document).ready(function() {
  $("#myDropDown").change(onDropDownChanged);
}

The first time the change handler is fired, it does the ajax update, and the text box is focused.

However, on subsequent changes, it continues to do the ajax update, but the text box is never focused again.

I found that if in onDropDownChanged, I added $("#updatePanel").empty() before the ajax call, the text box would always get focused. The problem with that is the entire form disappears for a second, causing an ugly flash. Given ajax is supposed to make things like this nice, it's not a workaround I want to use.

+4  A: 

It seems like it should work, but I wonder if the DOM isn't updated by the time the callback is invoked. You might want to see if introducing a delay helps.

function onPanelLoaded() {
     setTimeout( function() { $("#theTextInput").focus(); }, 500 );
}

Including the HTML on the page and what is returned via load() would be helpful if this doesn't work.

tvanfosson
This was my guess as well... although it isn't what is in the documentation. Seeing the HTML would certainly help sort it out.
TM
Setting a delay ought to work, even if the delay is 0. Sometimes all that's needed is to "defer" the call so that content inserted via `innerHTML` is available to the DOM.
savetheclocktower
A: 

Thank You tvanfosson ! I've had exactly the same problem !!! I couldn't focus on a ajax loaded input (the input was contained into some html code served to the ajax load() ).

A: 

Tvanfosson's advice solved a similar problem for me, thank you :)

Tom
Hi Tom. SO isn't a forum. If you don't have an answer, it should be added as a comment to the main question or someone else's answer (in this case tvanfosson's).
Justin Johnson
+1  A: 

I had a similar problem with IE6 and IE7, but setTimeout() was not a reliable solution. Sometimes it worked, sometimes it did not. It didn't work on some machines at all, and the 500ms value was completely arbitrary anyway. The focus() function worked exactly as expected without any timeout in both Firefox and Chrome, of course.

My solution was to call focus() twice for IE:

function onPanelLoaded() { var panel = $('#theTextInput'); panel.focus(); panel.focus(); }

Now THAT did what I intended in the first place.

Chris
this really works for me.. thanks bro
Jeeva S