How to change a <select> value from JavaScript

后端 未结 10 1497
一生所求
一生所求 2020-11-27 18:36

I have question that seems very simple, but I just can\'t get it right. I have a

提交评论

  • 2020-11-27 18:56

    You can use the selectedIndex property to set it to the first option:

    document.getElementById("select").selectedIndex = 0;
    
    0 讨论(0)
  • 2020-11-27 19:04

    Setting .value to the value of one of the options works on all vaguely-current browsers. On very old browsers, you used to have to set the selectedIndex:

    document.getElementById("select").selectedIndex = 0;
    

    If neither that nor your original code is working, I wonder if you might be using IE and have something else on the page creating something called "select"? (Either as a name or as a global variable?) Because some versions of IE have a problem where they conflate namespaces. Try changing the select's id to "fluglehorn" and if that works, you know that's the problem.

    0 讨论(0)
  • 2020-11-27 19:04
     <script language="javascript" type="text/javascript">
            function selectFunction() {
                 var printStr = document.getElementById("select").options[0].value
                alert(printStr);
                document.getElementById("select").selectedIndex = 0;
            }
        </script>
    
    0 讨论(0)
  • 提交回复
    热议问题