Firefox ignores option selected=“selected”

2020-01-27 11:17发布

If you change a dropdown and refresh the page, Firefox seems to ignore the selected attribute.

<option selected="selected" value="Test">Test</option>

It will in fact select the option you had previously selected (before the refresh). This ends up being a problem for me since there is an event triggered on the dropdown which changes other things. Is there a way to make firefox stop this behavior (other than firing another event when the page loads)?

20条回答
走好不送
2楼-- · 2020-01-27 11:52

enclose select in form attribute and it will work.

<!-- will not work in firefox -->
<option selected="selected" value="Test">Test</option>

and

<!-- this will work in firefox -->
<form>
 <option selected="selected" value="Test">Test</option>
</form>
查看更多
虎瘦雄心在
3楼-- · 2020-01-27 11:55

Try to disable autocomplete attribute of select input ... sometimes browser ignore select because of that

查看更多
Fickle 薄情
4楼-- · 2020-01-27 11:55

This is my solution:

var select = document.getElementById('my_select');
for(var i=0; i < select.options.length; i++){
    select.options[i].selected = select.options[i].attributes.selected != undefined;
}

I just put that at the top of the page (with appropriate id set), and it works for me. Replacing the getElementById with a loop over all selects on the page, I leave as an exercise for the reader ;).

查看更多
混吃等死
5楼-- · 2020-01-27 11:57

autocomplete wasn't working for me either.

This is the javscript fix written in jquery that i use:

$('input[type="radio"][selected]').click();
查看更多
ら.Afraid
6楼-- · 2020-01-27 11:59

Add autocomplete="off" HTML attribute to every select tag. (source: https://stackoverflow.com/a/8258154/260080)

This fixes the ODD behavior in FireFox.

查看更多
Luminary・发光体
7楼-- · 2020-01-27 11:59

use .prop() instead of .attr()

This does not work in firefox.
  $( 'option[value="myVal"]' ).attr( 'selected', 'selected' );
use this one
  $( 'option[value="myVal"]' ).prop( 'selected', 'selected' );

In other way
  $( this ).prop( 'selected', 'selected' );
查看更多
登录 后发表回答