post icon

Javascript function to uncheck all checkboxes

Yesterday I searched and searched for a good hour for some unobtrusive javascript to set all check boxes within a div to unchecked when a user would click “None” for a none of the above type form, when I realized that, duh I know how to write javascript. So I wrote this function.

Javascript:

function $(id) {
 return document.getElementById(id);
}
window.onload = initPage;
function initPage() {
 var productDiv = $("products");
 var productList = productDiv.getElementsByTagName("input");
 var productReset = $("product-none");
 productReset.onmouseup = function() {
  for (i = 0; i < productList.length-1; i++) {
   productList[i].checked = false;
  }
 }
}

HTML:

input value="1" name="product[]" id="Carpeting" type="checkbox" Carpeting
input value="2" name="product[]" id="Hardwood Flooring" type="checkbox" Hardwood Flooring
input value="3" name="product[]" id="Ceramic Tile" type="checkbox" Ceramic Tile
input value="4" name="product[]" id="Ceramic Tile" type="checkbox" Ceramic Tile
input value="5" name="product[]" id="Kitchen/Bathroom Cabinets" type="checkbox" Kitchen/Bathroom Cabinets
input value="6" name="product[]" id="Counter Tops" type="checkbox" Counter Tops
input value="7" name="product[]" id="Major Appliances" type="checkbox" Major Appliances
input value="32" name="product[]" id="product-none" type="checkbox" None

I’ve taken out the html tags cause it was causing this page to format wrong so you’ll have to just understand how the tags would look. Someone tell me how to get around this?

So basically this javascript creates an window onload then finds the div with id => “products”. Then finds all the input elements and puts them into an array. Then finds the input with the id => products-none. Then creates a function to run a for loop across the array and sets all check boxes value “checked” to false when a user releases a mouse click on the products-none input.

I’ve only tested this in Firefox 2.0 Mac OS X
Feel free to use it modify or what ever you like!

No comments yet.

Leave a comment