Javascript – Automatically making a div appear based on status of radio button with JavaScript

domformsjavascript

I have a form which posts data to the same page. Based on the user's radio button selection I am inserting checked="checked" into the radio button form element to redisplay the correct selection. This works fine, however when the form is redisplayed (in case of bad input etc), I need a div to be revealed (containing the relevant fields from the form).

I have an onclick event that reveals the div in the first place (before the user has posted the form), and this works fine, but when I redisplay the form I don't want the user to have to manually reveal the form again by clicking.

Therefore I've been trying something along the following lines (heavily cut down for the purposes of this post)…

<link href="styles/style1.css" rel="stylesheet" type="text/css" />
 <script language="JavaScript"> 
  if (document.getElementById('complete_yes').checked) {
   document.getElementById('repair_complete').style.display = 'block';
   } else {
     document.getElementById('repair_complete').style.display = 'none';
  }
 </script>
 <form action="javascript_test.php" method="POST">
  <input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
  <input id="complete_no" type="radio" name="complete" value="false"/>No
  <input type="submit" value="Save">
   <div id="repair_complete">
    I'm a div!
   </div>

… but it returns an Object Required javascript error (as it does in the 'real' page):

Message: Object required
Line: 3
Char: 1
Code: 0
URI: http://localhost/repair_system/javascript_test.php

Why is this? Am I not correctly referencing the form element? Apologies if I'm being a "div" (deliberate bad pun intended!), I'm yet to learn about the fun and games of javascript!

Best Answer

Because your javascript is not wrapped inside a function, the browser is executing it as soon as it "gets to it". In this case, the JS is being executed before the browser has reached the html declaring your form.

The simplest fix therefore is to move the Javascript to after your form. A more robust solution would be to wrap you code in a function, and have that triggered somehow - from what you appear to be trying to do, in this case it'll be the onLoad event of the body tag:

<head>
<script language="JavaScript"> 
  function showHelpDiv() {  
    if (document.getElementById('complete_yes').checked) {
     document.getElementById('repair_complete').style.display = 'block';
    } else {
     document.getElementById('repair_complete').style.display = 'none';
    }
  }
</script>
</head>
<body onload="showHelpDiv()">
 <form action="javascript_test.php" method="POST">
  <input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
  <input id="complete_no" type="radio" name="complete" value="false"/>No
  <input type="submit" value="Save">
   <div id="repair_complete">
    I'm a div!
   </div>