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/
- You don't stop the function
printColorAndGroup
with a}
. - You should use an object for key/value pairs, not an array.
- You might want to use the literal notation for an object.
- Inside the
onchange
function, you can pass the select withthis
. Soselect.options[...]
would then be possible and cleaner. - 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];
}
精彩评论