Can't focus input field in DOM loaded with ajax call

∥☆過路亽.° 提交于 2020-01-01 17:02:09

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/766566/cant-focus-input-field-in-dom-loaded-with-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!