Form Javascript

html forms offer a rich set of tools for different kinds of interaction. The concept of an element with a very specific behaviour, holding one or more values, originated with the desire to send some type of user input to the server. With Javascript the uses of checkboxes, radio-buttons and select lists can be greatly enhanced.

Attack of the checks

This Javascript manipulates the checked state of each box in a group of checkbox elements in an html form. The first two buttons speak for themselves, as no collection of checkboxes seems to go without them these days. The third button reverses all boxes regardless of their current state—this may not be the most useful part of the script. There are several sets of checkbox collections to show the discrimination that is made between them; the boxes and buttons for each have corresponding name attributes which the code relies on. The native reset method of the form happens to function as a master ‘Clear All’ as the form contains only checkboxes and each starts life empty...

Perhaps the most interesting part of the script allows the (un)checking of a whole range of checkboxes by holding the Alt or Ctrl key while clicking the second clicked end of the range. The range will be checked or unchecked according to the state of the last clicked box. And although the event handlers are set on the checkbox elements, any clicks on their accompagning text labels are handled just the same way. Shift should not be used as the magic modifier key, as it would select the text in the labels, which on most systems is the default action associated with Shift-clicks. A Ctrl-click selects single words on certain machines. These actions can of course be countered with some more script, but hardly in any balanced manner.

Check this quiz


Do you know your history?
Please name the Kings of England.


Would you mind some biology?
Please mark the four-legged animals.


How well is your math?
Please check the prime numbers.

The script

It should all speak for itself. If not, mouse over or doubleclick something.

function checkrange(e) {
 e = e || window.event || {};
 var f = this.form.elements, dir, i, j, l = this.form.lastclicked, c = this.checked, name = this.name;
 if( l && ( e.ctrlKey || e.altKey ) ) {
  i = +l.index;
  j = +this.index;
  dir = i>j ? -1 : 1; 
  for( ; i*dir < j*dir && f[i].name===name; i+=dir ) {
   f[i].checked = c;
 this.form.lastclicked = this;

function checkall( obj, how ) {
 var f = obj.form.elements, i = f.length, name = obj.name, o;
 while(i--) { o = f[i];
  if( o.type==='checkbox' && o.name===name ) { o.checked= how===2 ? !o.checked : how; }
 return false;

function checkini() {
 var f = document.forms.f.elements, i = f.length, o;
 while(i--) { o = f[i];
  if( o.type==='checkbox' ) { o.index = i; o.onclick = checkrange; }

checkini();  // perhaps onload