Reputation:
I tried to change the colors of the select lists header, title and text. I added the functions changehead()
, changetitle()
and changebody()
to do this. And bind elements through unique id.
But I'm getting the following error
Uncaught TypeError: Cannot read property 'undefined' of undefined
in the function changehead()
, after
header = document.form1.heading.options[i].value;
and in the function changetitle()
after
header = document.form1.heading.options[i].value;
I'm not sure whether I should be using two different functions or if it can be done with one.
Code:
<script>
function changehead() {
i = document.form1.heading.selectedIndex;
header = document.form1.heading.options[i].value;
document.getElementById("head1").style.color = header;
}
function changetitle() {
i = document.form1.heading.selectedIndex;
header = document.form1.heading.options[i].value;
document.getElementById("head2").style.color = header;
}
function changebody() {
i = document.form1.body.selectedIndex;
doccolor = document.form1.body.options[i].value;
document.getElementById("p1").style.color = doccolor;
}
</script>
</head>
<body>
<h1 id="head1">Controlling Styles with JavaScript</h1>
<hr>
<h2 id="head2">Subtitles at this screen. And cery important subtitles!</h2>
<hr>
<p id="p1">Select the color for paragraphs and headings using the form below. The colors you specified will be dynamically changed in this document. The change occurs as soon as you change the value of either of the drop-down lists in the form.</p>
<form name="form1"> <b>Heading color:</b>
<select name="heading" onChange="changehead();">
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
<br>
<B>Body text color:</B>
<select name="body" onChange="changebody();">
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
<br> <b>Heading second color:</b>
<select name="heading" onChange="changetitle();">
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
</form>
</body>
Questions:
Upvotes: 1
Views: 921
Reputation: 6773
You have two selects named "heading". Give them different names and your javascript will stop throwing errors.
Here is a working example: http://jsbin.com/uritid/1/edit
Upvotes: 1