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.
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();
}
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With