Focus Field: How to?


#1

How to focus a field when I click on icon? That is: I’ve a select field, but this field on mobile phone is transparent and the user don’t know where need to click.


#2

I can think of a few ways to do this, but could provide some code for your layout? This way I can give you the best answer that will fit your use case


#3

I’ve an icon that if I click on it “open” ( show ) a div with textbox or select field. Then after I click on icon I wish to position the focus on the field.


#4

Hi there,

I would do it like that:
Controller:

$scope.focusOnSelect: function(){
     document.getElementById('mySelect').focus();
}

Template:

<select ... id="mySelect" >...

<i class="..." ng-click="focusOnSelect()"></i>

Hope that helps :slight_smile:


#5

You should really use a directive for it.

.directive('triggerFocusOn', function($timeout) {
    return {
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                $timeout(function() {
                    var otherElement = document.querySelector('#' + attrs.triggerFocusOn);

                    if (otherElement) {
                        otherElement.focus();
                    }
                    else {
                        console.log("Can't find element: " + attrs.triggerFocusOn);
                    }
                });
            });
        }
    };
});

Then set your markup like so

<button trigger-focus-on="targetInput">Click here to focus on the other element</button>
<input type="text" id="targetInput">

#6

I tried that before, but this cause that select field don’t work ( I’m not able to choose values ).