-1

I have a HTML markup in a template which has input element. I load it via Ajax call and put in existing html using jQuery's $(selector).html(response).

Basically it is a pop up box which loads from template. After loading pop up box I want to set focus on input box. I've written this code :

$("#prescribe-input").focus() after content is appended in existing HTML but it does not work. I tried doing it in traditional javascript way too document.getElementById("prescribe-input").focus()

Both do not work. For testing purpose I tried creating sample input box in Index.html of an app and set focus. it works perfectly. The problem is when I load html from template using $().html() it does not work.

Any way to focus it properly?

I know the code is very less here but the question is self explanatory I believe.

Rahul Patil
  • 5,656
  • 6
  • 37
  • 65
  • 1
    You have to include minimal example which replicates your issue, it's unclear what is your issue, could be many things – A. Wolff Jul 01 '14 at 11:43
  • If the element existed and the selector was correct, setting the focus would work just fine on a dynamic element. – adeneo Jul 01 '14 at 11:43

2 Answers2

1

You should do this in the callback function:

$(selector).html(response, function(){
   $("#prescribe-input").focus();
})
Jai
  • 74,255
  • 12
  • 74
  • 103
1

if you are using jquery then you can use .on() on dynamically generated elements

$("#prescribe-input").on( "focus", function() {
  //do what ever you want
});
silk_route11
  • 324
  • 3
  • 17