I came across an irritating iOS select dropdown bug while testing a production site on an iPad. The bug occurs when the user tries to select the first option where no other options have been selected previously, either via user interaction or by default.
Unfortunately, the simplest fix, to place an empty, disabled option in the first position, is blocked by another bug. In iOS, disabled options are not disabled. See this articlefor more information.
Trying to fix this issue was like weaving a new subway tunnel under an old city (slight exaggeration!). The fix I came up with is to prepend an empty option into all selects that did not have an empty option in the first position, and had no options selected by default.
I’m only executing the fix on iOS devices using a simple if statement.
if(navigator.userAgent.match(/iP(ad|hone|od)/i)){
$('select').each(function(){
// set variables
var $this = $(this), // cache this
si = $this.attr('selectedIndex'), // find all selects that are not selected
$options = $this.find('option'), // make object of options
$firstOption = $options.filter(":first"); // filter first option
// disable any existing empty first options
if($firstOption.html() == ""){
$firstOption.attr('disabled', 'disabled');
}
// all selects that do not have a "selected" attribute
if (si === -1){
//add temporary style to see if/where it is working
//$this.css('border','2px solid green');
// prepend an empty, disabled option if none exist
if($firstOption.html() != ""){
$this.prepend('<option value="" disabled="disabled"></option>');
// set size +1
$this.attr('size', function(i, val){
return ++val;
});
}
}
});
}