Tutorial :When trying to remove any selected option in an select element, Safari shows it as blank



Question:

Examine this code. I'm using jQuery, but I think it is probably irrelevant.

JavaScript

​$(function() {      $('button').click(function() {        $('select option[selected]').removeAttr('selected');      });    });  

HTML

<select>      <option>a</option>      <option selected="selected">b</option>      <option>c</option>    </select>    <button>give me a click</button>  

This was working fine for having the button reset the select to the first option. I just tested it in Safari, and it blanks the select instead of selecting the first.

This isn't an issue, until I got it up and running on an iPad, which is where the majority of this web app will be used. The problem with the iPad is, after then selecting an option, the select refuses to display the option selected. It still displays as blank.

What is the best way to get around this?

​


Solution:1

You can fix the behaviour by explicitly setting the index using JavaScript's native selectedIndex property.

$(function() {      $('button').click(function() {        $('select option[selected]').removeAttr('selected');        $('select')[0].selectedIndex = 0;      });    });​  

If you have more than one select element, you will need to iterate through with jQuery's each and set the property on this.


Solution:2

What about:

$('select option:first-child').attr('selected', 'selected');  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »