Reputation: 8586
I am using Ajax to load parts of a form. How can I focus a textarea object after the ajax request?
This is the html loaded:
<legend>Test</legend>
<label for="t">This is only a test</label>
<textarea></textarea>
<a href="#" class="continue">Continue</a>
This is the JQuery/Ajax code:
$.post(
'ajax.php',
{ next:next },
function(data){
$('body').append($(data).hide().fadeIn('slow'));
}
);
Thanks.
Upvotes: 4
Views: 6949
Reputation: 1974
This snipped looks for an "autofocus" attribute in your HTML, and focuses on the given element.
$('[autofocus]').focus()
This way, if the view is loaded in Ajax, it works, and if there is no JavaScript and the view is loaded without ajax, you still get your autofocus.
Upvotes: 1
Reputation: 4399
Use .focus() trigger in your callback, after appending the html:
$.post(
'ajax.php',
{ next:next },
function(data){
$('body').append($(data).hide().fadeIn('slow'));
$('textarea').focus();
}
);
Upvotes: 9