Firefox not refreshing select tag on page refresh

佐手、 提交于 2019-11-28 01:18:32
Eliran Malka

FireFox will cache form values (including the selected value of a select box), when the refresh mechanism is activated normally (F5). However, if a user chooses to perform hard-refresh (Ctrl+F5), these values won't be fetched from the cache and your code will work as expected.

As users will act on their own will, you have to provide a solution to cover both cases. This can be done by taking several approaches:

  • Handle each page refresh: add some reset code to set the default selected state inside the window.onbeforeunload event listener.
  • Add that code at the beginning of the DOM ready handler.
  • Use cookies, as described in this post from Ted Pavlic's blog, to detect the page refresh and act on it (placing the same code there).
  • Set no-cache headers on the server-side, thus forcing the relevant resources to be fetched.

References

Note: It has been suggested on the linked SO post, as well as here in the comments, to simply turn autocomplete off. This, however, is not the best solution — for two reasons: a. Compatibility: autocomplete is an HTML5 attribute, so we're restricting our implementation of choice, and b. Semantics: The aim is to handle the case of a page refresh. The autocomplete is intended for controlling session history caching and manage prompting of the form controls. Should this implementation change in the future, that solution will break.

I think I have more simple solution. Why not to set the select back to index 0 when document is ready? It could look like this:

$('.manufacturers').prop('selectedIndex',0);

So your script could look like this:

$(document).ready(function() {

    $('.manufacturers').prop('selectedIndex',0);

    $('.manufacturers').change(function() {
        var selected = $(this).find(':selected');
        $('ul.manulist').hide();
        if ($(this).val() == 'all') {
            $('.scroll-content ul').show();
        } else {
            $('.' + selected.val()).show();
            $('.optionvalue').html(selected.html()).attr(
                    'class', 'optionvalue ' + selected.val());
        }
    });
});

And after reload the select will be back to the first position.

If your select tag is inside a form you can just add the attribute autocomplete="off" to it and it will behave as expected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!