简体   繁体   中英

JavaScript pre-select drop down value

I'm trying to preselect a dropdown value, in this case "Ireland" under Phone Number. I have this JS to select it by name:

function setSelectedIndex(s, v) {
  for (var i = 0; i < s.options.length; i++) {
    if (s.options[i].text == v) {
      s.options[i].selected = true;
      return;
    }
  }
}
setSelectedIndex(document.getElementById('CountryCodeAlpha2'), "Ireland (+353)");

However it's not working and I don't see any console error relating to this JS. Link to page is here: http://partners.moneycorp.com/contactusit?rp=10447109

Many thanks.

Your code is giving this error: Uncaught TypeError: Cannot read property 'options' of null . You need to put your script in an onload method. I think the DOM is not loaded when you're trying to default the dropdown value. Put the following code in an onload method:

     <script type="text/javascript">
        function setSelectedIndex(s, v) {
            for (var i = 0; i < s.options.length; i++) {
                if (s.options[i].text == v) {
                    s.options[i].selected = true;
                    return;
                }
            }
        }
        setSelectedIndex(document.getElementById('CountryCodeAlpha2'), "Ireland (+353)");
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM