Cannot focus input field in DOM loaded with ajax call

I went crazy trying to figure out how to do this. The code looks something like this:

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

At the first start of the change handler, it updates ajax, and the text field focuses.

However, with subsequent changes, it continues to update ajax, but the text field no longer focuses.

I found that if in onDropDownChanged, I added $("#updatePanel").empty()before calling ajax, the text field will always be focused. The problem is that the whole form disappears for a second, causing an ugly flash. Ajax is supposed to make such things enjoyable, this is not a workaround that I want to use.

+3
source share
2

, , , DOM callback. , , .

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

HTML , load(), , .

+6

IE6 IE7, setTimeout() . , . , 500 . focus() , , - - Firefox, Chrome, .

, focus() IE:

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

, .

+4

Source: https://habr.com/ru/post/1706693/


All Articles