Section 7.4. Radio Buttons and Checkboxes


7.4. Radio Buttons and Checkboxes

Both radio buttons and checkboxes provide one-click option choosing, usually among a smaller number of options than a selection. They differ in that radio buttons allow one, and only one, choice; you can check as many checkboxes as you like.

Both types of form-input elements are grouped by name. Here's the syntax for a radio button:

<form name="someForm"> <input type="radio" value="Opt 1" name="radiogroup" />Option 1<br /> <input type="radio" value="Opt 2" name="radiogroup" />Option 2<br /> </form>

Notice that the name is the same for both options; that's how the buttons are grouped. The checkbox syntax is exactly the same, except the type is set to checkbox rather than radio.

To access the selected items, use the same functionality as selection, except that you check to see if the item is checked rather than selected:

   var buttons = document.someForm.radiogroup;    for (var i = 0; i < buttons.length; i++) {       if (buttons[i].checked) {          alert(buttons[i].value);       }    }

The only difference in processing between the two types is that the radio buttons have only one checked item.

It's hard to screw up with radio or checkboxes, so JiT validation makes little sense. You could match the behavior of the buttons with other form options, but if you need to restrict one or more radio buttons or checkboxes, a better option would be to disable the option, rather than validate it post-event.

You can disable the option using the following JavaScript:

document.someForm.radiogroup[1].disabled=true;

You can trap the click event for the group if you want to modify other form elements based on a radio button or checkbox selection. To attach an event handler, you attach it to the group:

document.someForm.radiogroup.onclick=handleClick;

Unlike selection, you don't dynamically add or delete options from a radio group or set of checkboxes. You can use dynamic HTML (DHTML) to hide options, but you're better off using the disabled property to manage the dynamic nature of the control.

7.4.1. The textarea, text, hidden, and password Input Elements

The text, textarea, and password fields are probably the most used, as well as the input elements most likely to need validation. The hidden field usually doesn't have a problem with validation, but it is a text-based field, so I've thrown it in with the group to keep like controls together.

The single-row text-based input elements are defined in XHTML as:

<input type="text|hidden|password" name="fieldName" value="Some value" />

Setting the type attribute defines the type of field. The text field is regular text, the hidden isn't visible to the person filling in the form, and the password field hides the text with asterisksjust in case someone is looking over your shoulder.

The textarea field is similar except that unlike the other input fields, it has an opening and closing tag, and you can set both column and row widths:

<textarea name="fieldName" rows=10 cols=10>Initial text</textarea>

In JavaScript, the values of the fields for all text input types are accessible via the form element value property. In Example 7-3, a form with all four types is defined, and when the form is submitted, JavaScript is used to access all four and build a string, which is then added back to the textarea input element.

Example 7-3. Accessing text-based input fields from JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Input form</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ if (window.addEventListener) {       window.addEventListener("load",setupEvents,false);    } else if (window.attachEvent) {       window.attachEvent("onload", setupEvents);    } else {       window.onload=setupEvents; } function setupEvents(evnt) {    if (document.someForm.addEventListener) {         document.someForm.addEventListener("submit",validateForm,false);     } else if (document.someForm..attachEvent) {         document.someForm.attachEvent("submit", validateForm);     } else {         document.someForm.onsubmit=validateForm;;    } } function validateForm(evnt) {    var strResults = "";    for (var i = 0; i < document.someForm.elements.length - 1; i++) {       strResults += document.someForm.elements[i].value;    }    document.someForm.elements[3].value = strResults;    if (evnt.preventDefault) {       evnt.preventDefault(  );    } else if (evnt.cancelBubble != null) {       evnt.cancelBubble = true;    }         return false; } //]]> </script> </head> <body> <form name="someForm"> <input type="text" name="text1" /><br /> <input type="password" name="text2" /><br /> <input type="hidden" name="text3" value="hidden value" /> <textarea name="text4" cols="50" rows="10">The text area</textarea> <input type="submit" value="Submit" /> </form> </body> </html>

In the example, the code accesses only the first four form elements because the fifth is the submit button. It does have a value, just not one we're interested in. Also notice in the code that the form submission is canceled. If we didn't cancel the submittal, the form fields would be reset, and we'd lose the string just created.

Also in the example, DOM Level event handling is used for all of the functionality, including canceling the form submission using defaultPrevent or cancelBubble in the form's validation code.

7.4.2. JiT Does Text

Text fields are the form elements most likely to have bad data resulting from a misunderstanding of what's required or typographical errors. As such, it is these fields you'll most likely want to implement with JiT validation.

The events of interest for JiT with text-input elements are change, focus, and blur. When the cursor moves into a text-input field, a focus event is fired; when the cursor leaves, the blur event is triggered. A change event happens when the cursor moves out of the field, and whatever contents were in the field are changed. Both are important because a user could click or tab into a field but not make any change, in which case the change event wouldn't fire. In these cases, you want to use the blur event to make sure the field has some valueif it's a required field, of course.

Modifying the application in Example 7-3, the blur event is trapped for the password field, and the value checked to make sure some entry is made in the new application in Example 7-4. In addition, when the first field is changed, the value is validated against a regular-expression pattern for a Social Security number with a pattern of: nnn-nn-nnnn.

Example 7-4. Applying Just-in-Time validation with text-based input fields

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>JiT RegEx</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ if (window.addEventListener) {       window.addEventListener("load",setupEvents,false);    } else if (window.attachEvent) {       window.attachEvent("onload", setupEvents);    } else {       window.onload=setupEvents; } function setupEvents(evnt) {    document.someForm.text2.onblur=checkRequired;    document.someForm.text1.onchange = validateField; } function checkRequired (evnt) {   var theEvent = evnt ? evnt : window.event;   var target = evnt.target ? evnt.target : evnt.srcElement;   var txtInput = target.value;   if (txtInput == null || txtInput == "") {      alert("value is required in field");   } } function validateField(evnt) {   var theEvent = evnt ? evnt : window.event;   var target = evnt.target ? evnt.target : evnt.srcElement;   var rgEx = /^\d{3}[-]?\d{2}[-]?\d{4}$/g;      var OK = rgEx.exec(target.value);   if (!OK) {      alert("not an ssn");   } } //]]> </script> </head> <body> <form name="someForm"> <input type="text" name="text1" /><br /> <input type="password" name="text2" /><br /> <input type="hidden" name="text3" value="hidden value" /> <textarea name="text4" cols=50 rows=10>The text area</textarea> <input type="submit" value="Submit" /> </form> </body> </html>

Now, if the SSN doesn't have the proper format, you'll get notified as soon as you leave the field. In addition, if a password isn't provided, another pop up opens. Of course, pop ups get irritating over time, and later in the book we'll look at better ways of providing feedback.

This example also demonstrates how important regular expressions are with any form of user input. The last section of this chapter looks at applying regular expressions to text input.

Use extreme care if you decide to enforce a required field using the focus method to return the cursor to the fieldespecially in combination with a pop-up window giving an error. In some browsers, such as Opera, this can trigger a neverending loop. It can also irritate your users considerably. Bottom line, I would advise against enforcing a required field through the use of focus.

JavaScript Best Practice: Don't enforce a required field using focus to force the person back to the field. It's better to provide a more passive approach.





Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net