3

I have a large form and I would like when the user clicks a "new" button for the focus to be placed in a specific input field. There's a grid on the form and every field has a known id. Note it might not be the first field so not easy to use the tab.

Would appreciate some advice if this is possible. Would save having to manually have the user move the cursor over and click in the input field.

Update: Changed "move cursor" to "change focus"

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • you can use `focus` event – pwolaq Oct 05 '16 at 12:44
  • Just curious why you think it's better UX to move the user's mouse for them. That's really jarring and disorienting. I'd suggest an alternative approach, like just focusing as pwolaq suggests. – ryanyuyu Oct 05 '16 at 12:49
  • yes your correct. I would like to use the focus event but not quite sure how to do this. Thanks – Alan2 Oct 05 '16 at 12:55
  • You need a directive for that, so you can track focus status. This answer of mine to different question might be helpful: http://stackoverflow.com/a/17739731/158523 – Umut Benzer Oct 05 '16 at 12:58
  • Good link about angularJS input field focus: http://stackoverflow.com/questions/14833326/how-to-set-focus-on-input-field – CroMagnon Oct 13 '16 at 14:16

4 Answers4

3

Here is one solution -

Angular js gives you an advantage of using some of the extra features so that you dont have to use the jquery.

Here is one way to implement the autofocus feature.

<div class="button" input-focus>{{element.idORname}}</div>

and the directive to be defined here.

.directive("inputfocus",function($timeout){
           return {
                    link : function(element,attributes){
                    element.bind('click',function($timeout){
                       $timeout(function(){
                          element/*.parent() or.child()*/.find('type of the field you want to select')[0].focus();
                          );
                        );
                      );

Here you can use the javascript or jquery methods for the dom traversal if there are nested fields in your code.

$timeout is necessary to call for the focus after the browser renders when user has finished clicking the event

As you can see the find('')[0] is a replacement for find('').focus as the latter requires jquery to be used.

Pritish Vaidya
  • 21,561
  • 3
  • 58
  • 76
1

Place "autofocus" attribute on the element that you want to focus.

Example:

Name: <input type="text" name="name" autofocus />
ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
Thirumalai
  • 11
  • 1
1

If all the input ids are known, just use that.

$("#NewButton").on('click', function(){
    //Other code.
    $("#IdOfInputToBeFocused").focus();
});
Jacobalo
  • 233
  • 1
  • 4
  • 13
0

Custom data attribute can be used with jQuery like this

<input data-field="special" />

And then that specific field can be called like this

jQuery('input').find("[data-field='special']").focus();

Arsalan
  • 461
  • 3
  • 12