views:

59

answers:

2

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?

+2  A: 

Hello sir :P

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.

alex
+1  A: 

What about:

$('select option:first-child').attr('selected', 'selected');
sje397
Close, but I think that selector will need to be `select option:first-child`. Fix that and you have a +1 from me :)
alex
Done. Thanks @alex.
sje397