Reputation: 1
I am trying to access the style attribute of a element in order to display a form however, I get this error: Uncaught TypeError: Cannot read property 'style' of undefined. The example below is a simplified example.
cookies.php
echo "[a href='test.php?flavor=butter']Bake Butter Cookies[/a]";
echo "[a href='test.php?flavor=chocolate'] Bake Chocolate Cookies [/a]";
?>
test.php
switch($cookieType){
case "chocolate":
echo "<script type='text/javascript'>";
echo "document.chocolate.style.display='block'; ";
echo "</script>";
break;
case "oatmeal-raisin":
echo "<script type='text/javascript'>";
echo "document.oatmealraisin.style.display='block'; ";
echo "</script>";
break;
case "butter":
echo "<script type='text/javascript'>";
echo "document.butter.style.display='block'; ";
echo "</script>";
break;
}
?>
<div id="chocolate" style="display:none;">
<form action="<?php echo $_SERVER['php_self']?>">
<input type="hidden" name="type" value="chocolate"/>
What is your name: <input type="text" name="your_name"/>
How many chocolate chips on each cookie? <input type="text" name="chips"/>
How many many cookies? <input type="text" name="cookies"/>
<input type="submit" name="BAKE!"/>
<input type="reset"/>
</form>
</div>
<div id="oatmealraisin" style="display:none;">
<input type="hidden" name="type" value="oatmealraisin"/>
<form action="<?php echo $_SERVER['php_self']?>">
What is your name: <input type="text" name="your_name"/>
How many raisins on each cookie? <input type="text" name="raisins"/>
How many many cookies? <input type="text" name="cookies"/>
<input type="submit" name="BAKE!"/>
<input type="reset"/>
</form>
</div>
<div id="butter" style="display:none;">
<form action="<?php echo $_SERVER['php_self']?>">
<input type="hidden" name="type" value="butter"/>
What is your name: <input type="text" name="your_name"/>
How many many cookies? <input type="text" name="cookies"/>
<input type="submit" name="BAKE!"/>
<input type="reset"/>
</form>
I have never had problems accessing the style attribute of a element before so I am not sure what is the problem. The switch statement does work because the javascript console shows the output of the right case. I need another pair of eyes. Any suggestions?
Upvotes: 0
Views: 288
Reputation: 700152
It's not the style attribute that is the problem, you failed to access the elements themselves.
You are trying to access the elements as if they are global variables in the document object, that is only true in IE in quirks mode. You need to use the getElementById method. Replace:
document.chocolate
with:
document.getElementById('chocolate')
and corresponding for each element.
Upvotes: 2