开发者

Need to fill multiple text fields when a drop down menu option is chosen

开发者 https://www.devze.com 2023-04-05 18:02 出处:网络
For some reason this code doesn\'t work in IE9 (could not try other开发者_开发问答 versions of IE). When tried it worked fine in Chrome and Firefox.. Text boxes comes up with message "undefined&q

For some reason this code doesn't work in IE9 (could not try other开发者_开发问答 versions of IE). When tried it worked fine in Chrome and Firefox.. Text boxes comes up with message "undefined" when a drop down item is selected.

I am not able to figure out whats wrong, I wanted this working primarily in IE9... Any help is greatly appreciated..

Code: http://jsfiddle.net/pimvdb/RemPF/1/


  1. You don't stop the function printColorAndGroup with a }.
  2. You should use an object for key/value pairs, not an array.
  3. You might want to use the literal notation for an object.
  4. Inside the onchange function, you can pass the select with this. So select.options[...] would then be possible and cleaner.
  5. Instead of names, you can also use IDs, so you don't have to worry about [0] each time.

Altered version: http://jsfiddle.net/pimvdb/RemPF/1/


This is a literal object notation:

var colors = { apple:   "red",
               grape:   "purple",
               milk:    "white",
               cheese:  "yellow",
               chicken: "white",
               beef:    "red"    };

This is how IDs work:

<input type="text" id="food_group" ...>

And you can fetch the element with:

document.getElementById('food_group')

This is how passing the select works:

<select name="food" onchange="printColorAndGroup(this)">

with the following JavaScript:

function printColorAndGroup(select){
var text = select.options[select.selectedIndex].value;
...


You're missing a closing } before your </script> tag

function printColorAndGroup(){
    var text = document.getElementsByName('food')[0].options[document.getElementsByName('food')[0].selectedIndex].value;
    document.getElementsByName('food_group')[0].value = groups[text];
    document.getElementsByName('food_color')[0].value = colors[text]; 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消