You may have come across a situation where the autofocus does not work in when a new text field is generated through AJAX.
I had a situation where I was showing a web form and I wanted the first text field to focus, I would see it focus but it would immediately go out of focus. I tried everything until I finally found the solution.
The solution is very easy actually, all you have to do is delay the this.focus(); function by using the setTimeout() function.
This is a perfect example what script you can use: