简体   繁体   中英

On an iPad, how can you set focus() on a select element via Javascript event without showing options?

We use JavaScript to create and display a form, and then set focus on the first control on the form, which happens to be a select element. On an iPad with iOS 8 or iOS 9, Chrome, Safari, and Firefox will set focus on the select element and reveal the select options with the following JavaScript code:

 document.getElementById("button1").onclick = function() { document.getElementById("selectCtrl1").focus() }; 
 <!DOCTYPE html> <html> <body> <div> <button id="button1">Click Me!</button> </div> <div> <select id="selectCtrl1"> <option value=1>red</option> <option value=2>green</option> <option value=3>blue</option> </select> </div> </body> </html> 

If "onclick" is changed to "ontouchend", when the "Click Me!" button is pressed, focus is set on the control, the options are briefly shown, and then focus is removed from the select control. If you run the above code on a desktop computer, focus is simply set on the select control. Furthermore, on an iPad, if you were to set focus on the select control in JavaScript when the page is loaded, focus would be simply set on the select control.

So, how should one set focus on a select control as a result of an event without revealing the options?

For what it is worth, we do not leverage third party libraries and prefer answers that only employ JavaScript.

How about wrapping the .focus() call in an immediate setTimeout?

I'm testing on my iPad and it appears to be triggering focus without any initial dropdown showing.

 document.getElementById("button1").onclick = function() { setTimeout(function() { document.getElementById("selectCtrl1").focus(); },0); }; 
 <!DOCTYPE html> <html> <body> <div> <button id="button1">Click Me!</button> </div> <div> <select id="selectCtrl1"> <option value=1>red</option> <option value=2>green</option> <option value=3>blue</option> </select> </div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM