ch08-04.html 1.88 KB
Newer Older
O'Reilly Media, Inc.'s avatar
O'Reilly Media, Inc. committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Checkbox</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
//<![CDATA[

function catchEvent(eventObj, event, eventHandler) {
   if (eventObj.addEventListener) {
       eventObj.addEventListener(event, eventHandler,false);
   } else if (eventObj.attachEvent) {
       event = "on" + event;
       eventObj.attachEvent(event, eventHandler);
   }
}

function cancelEvent(event) {
   if (event.preventDefault) {
       event.preventDefault();
       event.stopPropagation();
   } else {
       event.returnValue = false;
       event.cancelBubble = true;
   }
}

catchEvent(window,"load",setupEvents);

function setupEvents(evnt) {
  catchEvent(document.getElementById("someForm"), "submit",checkColors);
}

function checkColors(evnt) {

   var theEvent = evnt ? evnt : window.event;
   var colorOpts = document.getElementById("someForm").getElementsByTagName("input");

   // check through input elements for checkbox and checked
   var isChecked = false;
   for (var i = 0; i < colorOpts.length; i++) {
     if ((colorOpts[i].type == "checkbox") && (colorOpts[i].checked)) {
       isChecked=true;
       break;
     }
   }

   // none were checked
   if (!isChecked) {
      alert("You must check one of the four color checkboxes");
      cancelEvent(theEvent);
   }
}

//]]>
</script>
</head>
<body>
<form id="someForm" action="">
  <p>
  <input type="checkbox" name="color1" value="red" /> : red<br />
  <input type="checkbox" name="color2" value="blue" /> : blue<br />
  <input type="checkbox" name="color3" value="green" /> : green<br />
  <input type="checkbox" name="color4" value="yellow" /> : yellow<br /><br />
  
  <input type="submit" value="Submit" />
</p>
</form>
</body>
</html>