1

I have a fiddle : http://jsfiddle.net/SDr3F/10/

Currently:

onclick, it alerts

alert('hi')  

Required:

onclick, it loads a search.html with a search text box and focus in textbox

search.html

<input id="search-input" type="text" class="input-medium search-query span4">  

How I set focus?

$(function(){
  $("#search").click(function(){
      $('#feature').load('templates/search.html');
      $('#search-input').focus();
      alert("hi");
  });
});

Problem

  • It loads the page BUT doesn't focuses inside textbox, how do I fix this?
daydreamer
  • 87,243
  • 191
  • 450
  • 722

2 Answers2

5

In your example you focus element right after the Ajax request is made but not when the request is successfully completed. Hence, you try to focus the element that is not yet loaded.

You should add the complete handler. The following should work:

$("#search").click(function() {
    $("#feature").load("templates/search.html", function() {
        $("#search-input").focus();
    });
});​
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • +1, but are you going to explain why it needs to be in a callback so that the OP knows for next time? – Paul Jun 22 '12 at 21:46
  • Awesome, thanks much, I tried with callback before but it didn't work(I am sure, I did not do it correctly), but yeah, why it needs to be in callback? – daydreamer Jun 22 '12 at 21:48
  • 1
    @daydreamer The Ajax request works asynchronously. The callback will be executed when all the content from "search.html" is loaded, and with that you can do the element focusing. Otherwise, the "search-input" element won't exist. – VisioN Jun 22 '12 at 21:55
2

You need a callback so that it knows that the content of the page is fully loaded before it tries to set the focus.

Vartan Arabyan
  • 2,925
  • 7
  • 25
  • 35