Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: focus textarea after ajax load

Tags:

jquery

ajax

focus

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.

like image 875
Roger Avatar asked Dec 27 '22 12:12

Roger


2 Answers

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();
    }
);
like image 156
gustavotkg Avatar answered Jan 15 '23 07:01

gustavotkg


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.

like image 29
Brachamul Avatar answered Jan 15 '23 08:01

Brachamul