Focusing an input field in Ionic not working
17,518
You could use autofocus
, but that will work only first time you open page,so try this directive. It works like a charm for me.
JS:
angular.module('app').directive('focusMe',['$timeout',function ($timeout) {
return {
link: function (scope, element, attrs) {
if (attrs.focusMeDisable === "true") {
return;
}
$timeout(function () {
element[0].focus();
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.show(); //open keyboard manually
}
}, 350);
}
};
}]);
HTML:
<input type="text" id="firstName" placeholder="First Name" ng-model="registerData.firstName" focus-me focus-me-disable={{disableFlag}}>
Author by
Admin
Updated on June 22, 2022Comments
-
Admin almost 2 years
I've been doing my research and it seems that this is not an uncommon issue or question in the Ionic community. I have a simple form with a view inputs:
<input type="text" id="firstName" placeholder="First Name" ng-model="registerData.firstName"> ...
In my controller I then try to focus the field:
document.getElementById("firstName").focus();
Of course it doesn't work, so as a few posts that I've seen suggests, I have to add the Ionic Keyboard Plugin . I do so by running:
cordova plugin add https://github.com/driftyco/ionic-plugins-keyboard.git
And then I apparently have to set this in my
config.xml
as wel:<preference name="KeyboardDisplayRequiresUserAction" value="false"/> <feature name="Keyboard"> <param name="ios-package" onload="true" value="IonicKeyboard"/> </feature>
And then apparently everything should work... but it doesn't. Is there something I'm missing?
-
Admin over 8 yearsHi @mudasserajaz when I use your directive. It gives focus to whichever input has the directive regardless of whether it's true or false..?
-
Mudasser Ajaz over 8 yearshey @DeanGrobler i have updated html. You can control disableFlag from controller now.
-
domoindal almost 8 years@MudasserAjaz, your solution works fine in my browser but in iOS neither focus in textbox nor open the keyboard. Does it work for you?
-
S. Roose over 7 yearsIt works for me, but you need to add following to your config.xml: ` <preference name="KeyboardDisplayRequiresUserAction" value="false"/>`