How to let a textarea be focused when it shows?

1,327 views
Skip to first unread message

Freewind

unread,
Apr 9, 2012, 4:36:09 AM4/9/12
to ang...@googlegroups.com
See my demo: http://jsfiddle.net/Freewind/jJVQC/

I hope when I clicked the text and textarea is shown, it will be focused(the cursor will inside it and can input text).

How to do this?

Peter Bacon Darwin

unread,
Apr 9, 2012, 4:47:14 AM4/9/12
to ang...@googlegroups.com

I used this in my angular driven student grouping app (http://petebacondarwin.github.com/Student-Grouping-App/) - just stick autofocus on the textarea element: here is a fiddle http://jsfiddle.net/jJVQC/1/. Of course this doesn't work on all browsers.
Pete

... sent from my SAM Coupe

On Apr 9, 2012 9:36 AM, "Freewind" <nowi...@gmail.com> wrote:

Freewind

unread,
Apr 9, 2012, 5:27:25 AM4/9/12
to ang...@googlegroups.com
`autofocus` is good enough, thanks!

Ankur Gupta

unread,
Apr 7, 2015, 12:39:52 AM4/7/15
to ang...@googlegroups.com
But how can we resolve it if we have multiple such instances of showing text area in a view? I think in that case autofocus will not work. Check http://jsfiddle.net/ankurnecessary/0u55yr5j/

Sander Elias

unread,
Apr 7, 2015, 2:49:45 AM4/7/15
to ang...@googlegroups.com

Hi Ankur,

In such a case, use a direcive like this:

.directive('myFocus', function () {
   var ddo = {
        restrict : 'A', // only antribute
        link : function (scope, element, attrs) {
             scope.$watch(attrs.myFocus, function (newVal) {
                 if (!!newVal) {
                    element[0].focus();
                    // you might want to reset the myFocus here, so it works more then once.
                  }
              });
         }
       };
    return ddo;
};

Does that help?

Regards
Sander

Reply all
Reply to author
Forward
0 new messages