background
|
|
Computer

Linux
Linux Support
A small area on the internet for Linux Support.
More icon
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
Thau's JavaScript Tutorial
Lesson 5

by Thau!

Page 8 — Radio Buttons

Happily, radio buttons are almost exactly like checkboxes with respect to JavaScript. The only real difference is in the HTML. Checkboxes are on/off devices. If a checkbox is checked, you can uncheck it. If it's unchecked, you can check it. Radio buttons are different. Once a radio button is on, it stays on until another one is selected. Then the first one goes off. Here's a typical radio button set:

Larry
Moe
Curly

As you can see, you can't simply unselect a radio button, you have to choose a new one. With that in mind we can re-do the light switch example with two radio buttons instead of one checkbox:

Light off
Light on

This example looks very much like the checkbox example. The form is:

<form name="form_1">
<input type="radio" name ="radio_1" onClick="offButton();">Light off
<input type="radio" name ="radio_2" onClick="onButton();" checked>Light on
</form>

When the first radio button is clicked, the offButton() function is called. That function is:

function offButton()
{
  var the_box = window.document.form_1.radio_1;
  if (the_box.checked == true) 
  {
    window.document.form_1.radio_2.checked = false;
    document.bgColor='black';
    alert("Hey! Turn that back on!");	
  }

}

This is pretty much just like the checkbox example earlier. The main difference is this line:

window.document.form_1.radio_2.checked = false;

This tells JavaScript to turn off the other button when this button has been clicked. The function that is run when the other button is clicked is similar to this one:


function onButton()
{
  var the_box = window.document.form_1.radio_2;
  if (the_box.checked == true) {
    window.document.form_1.radio_1.checked = false;
    document.bgColor='white';
    alert("Thanks!");
  }
}

There are a few more details about checkboxes and radio buttons, but those can wait until the next set of tutorials. Right now, let's look at the last type of form element, selects.

next page»