Stupid Form Tricks - Using the DOM to Clear Form Elements

for IE5+, Netscape 6, Opera 6.05

Okay, here's the scenario:
- you have a form full of checkboxes, each with a different name
- you want to be able to clear all or some of them.

You could use document.formname.element to do it but that would take quite a bit of code.
Fortunately, using the getElementByTagName() and getAttribute() methods, the DOM let's you do it without having to name each item.

Not only does the DOM let you clear all the checkboxes using very little code, you can also create sections within a form and clear only the elements contained within them. In the form DOMdemo a section has been created using <div id="testDiv1">.

You'll find the scripts, one function for each button, at the bottom of the page.

<form name="DOMdemo">
   <div id="testDiv1">
IOC OPG CLO
WOW OB DNR
NH ND DNI
Yes No Maybe
   </div>
Red Green Blue
Left Center Right


</form>
<script language="javascript">
function clearAllCheckboxes(){
   // -- get all the input elements in the document
   var ckBx=document.getElementsByTagName('input') 	
   for (i=0; i<ckBx.length;i++) {
   // -- get only those inputs that are checkboxes
   if (ckBx[i].getAttribute('type')=='checkbox') {					
   ckBx[i].checked=false;
   }
   else { }
   }
   }
   
function cleartestDiv1Checkboxes(){
   // -- get the element with id 'testDiv1'
   var div=document.getElementById('testDiv1');	
   // -- get the input elements within 'testDiv1'			
   var ckBx=div.getElementsByTagName('input')			
   for (i=0; i<ckBx.length;i++) {
   // -- get only those inputs that are checkboxes
   if (ckBx[i].getAttribute('type')=='checkbox') {					
   ckBx[i].checked=false;
   }
   else { }
   }
   }
   
function clearAllInputs(){
   // -- get all the input elements in the document
   var ckBx=document.getElementsByTagName('input')	
   for (i=0; i<ckBx.length;i++) {
   ckBx[i].checked=false;
   }
   }
   </script>







PXL8 2003