How to set input focus?
Since I am pretty sure that someone will get this problem too, I decided to answer my own question.
So I've fixed the issue partly using this line of code:
myWebView.keyboardDisplayRequiresUserAction = false
I found the solution while reading the apple documentation for UIWebView.
Please see this reference.
Can't Set Focus in Safari
EDITED TO INCLUDE .focus()
Try
javascript:document.getElementById('identNum').focus().setSelectionRange(0, 999);
Mobile devices, in particular iOS can be quite funny about select();
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
EDIT: A note on input focus without user interaction
As found by @zappullae
It appears that in recent versions of iOS, Apple require user interaction in order to activate the keyboard, so this will not be possible on page load.
https://medium.com/@brunn/autofocus-in-ios-safari-458215514a5f
How to programmatically focus a text input in iOS, coming from a trusted onchange event of a select tag?
You probably found that there is a flag called keyboardDisplayRequiresUserAction
in Cordova project options. It can be set to false
to lift the restrictions on the use of focus()
in native iOS applications. For normal Web applications, however, I haven't seen any official documentation about these restrictions in iOS browsers.
After many unsuccessful attemps to make focus()
work with the select
element in iOS, the only workaround that I found is to use a replacement control, for example jQuery's select2, as illustrated in this jsfiddle. The CSS attributes could be refined to make it look more similar to the native select element.
The call to myTextInput.focus()
can be made in the mouseup
event handler of the list items, that handler having been set the first time the dropdown list was opened:
var firstOpen = true;
$(mySelect).select2({
minimumResultsForSearch: Infinity
}).on('change', function(e) {
console.log("change event was fired");
}).on('select2:open', function(e) {
if (firstOpen) {
firstOpen = false;
$('.select2-results ul').on('mouseup', function(e) {
myTextInput.focus();
});
}
});
Related Topics
Is There a Case Insensitive Jquery :Contains Selector
Difference Between Synchronous and Asynchronous Programming (In Node.Js)
How to Use Setinterval and Clearinterval
Best Way to Find If an Item Is in a JavaScript Array
How to Find the Operating System Details Using JavaScript
How to Get the Youtube Video Id from a Url
Why Are Global Variables Considered Bad Practice
Preloading Images With JavaScript
How to Find Object in Array by Property in JavaScript
Converting an Object to a String
Check If a Value Is an Object in JavaScript
How to Replace All Line Breaks in a String With ≪Br /≫ Elements
How to Debug Node.Js Applications
What Is the Significance of the JavaScript Constructor Property