简体   繁体   中英

Changing the selected option in a dropdown menu and so cause an onchange event; javascript

Well, I have spent quite a while fiddling round with this with little progress. I have seen plenty of solution however, implementing them into my situation isn't working and I really don't know why.

I am trying to make some images change the selected value of a dropdown menu upon being clicked and so causing an onchange event on the dropdown menu to occur.

<script type="text/javascript">
 function parse_theme(input){
    var index = document.getElementById('themes').length; /* this bit is working fine */
    for(var i=0;i<=index;i++;){
       if(document.getElementById('themes').options[i].value == input){ /*error is here */
          document.getElementById('themes').selectedIndex = i;
       }
    }
}
</script>

And the html:

<select id="themes" style="display:none;" onchange="selectTheme()">
  <option value="default" selected="selected">default</option>
  <option value="ambiance">ambiance</option>
  <option value="cobalt">cobalt</option>
</select>

<img id="default" onclick="parse_theme(this.id)" src="images/default.png" width="10" height="10">
<img id="ambiance" onclick="parse_theme(this.id)" src="images/ambiance.png" width="10" height="10">
<img id="cobalt" onclick="parse_theme(this.id)" src="images/cobalt.png" width="10" height="10">

And I'm recieving "Uncaught TypeError: Cannot read property 'value' of undefined.

The onchange function works fine, when I simply have the dropdown menu however, I wanted it to be done through a sequence of images and have the images refer to the options in the list and have the list to be invisible.

Change it to

for(var i=0;i<index;i++;){

You are probably failing for the last index of the loop since index value will be 3 you will loop for 0,1,2,3 instead of only 3 times

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