Form input=”checkbox” clearing

Posted by Phil on February 19, 2008 under Javascript | Be the First to Comment

So it turns out that there is a fairly-easy way, and a wicked-easy way to handle almost things you come across. And if it feels like it’s way to hard, I’m pretty sure it is. Needless to say we were on the NordicTrack site working on a form for the ‘compare’ feature, and we needed to clear all the check-boxes on the page whenever certain buttons are pressed (the ‘bug’ so that it would compare the two items listed in the series). We finally ended up with this nice little loop (lifted partially from a google code site)

var frm = document.selectionform;
var el = frm.elements
for(i=0;i<el.length;i++){
if(el[i].type == "checkbox"){
el[i].checked = false;
}
}

Now while this is super-great, I knew that it could be better done since we are incorporating Prototype into the project, but I couldn’t remember the command that would make this better. Well, I just stumbled on to it. What we needed was a one liner.

Form.reset(formname)

That’s it, that would have fixed the entire thing, no looping, no extra variables, just that line. Now if you use this in your own code elsewhere, remember that it erases everything from your form, not just check-boxes.