We can dynamically check and un-check radio buttons with javascript. The basic syntax is:
button.checked = true (checks a radio button)
button.checked = false (unchecks a radio button)
checked is a property of the radio button object. Have a look at this...
<html> <head> <title></title> <script type="text/javascript"> function FruitBox() { window.document.myform.fruit[0].checked = true; } </script> </head> <body> <form name="myform"> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'oranges'">Oranges & Tangerines<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'bananas'">Bananas<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'peaches'">Peaches, Nectarines & Plums<br> To select Oranges <a href="javascript:FruitBox()">click here</a>. </form> </body> </html>
See what's going on? The group of radio buttons is an array... fruit[0], fruit[1] and fruit[2], and can be referenced as such. The function basically says, check the first element in that group, which happens to be Oranges.
Exercise: Slightly alter the script to check bananas when the link is clicked.
Exercise: rather than having the number (0, 1 or 2) hard coded into the function, send it a number from the link. Send it 2 for peaches.
Now we'll add two more links, one for each fruit...
To select Oranges click here.
To select Bananas click here.
To select Peaches click here.
We'll also add a fourth line that grabs the current value and throws it up in an alert box...
To read the current value click here.
Here is what we have to this point...
<html> <head> <title></title> <script type="text/javascript"> function FruitBox(whichfruit) { window.document.myform.fruit[whichfruit].checked = true; } </script> </head> <body> <form name="myform"> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'oranges'">Oranges & Tangerines<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'bananas'">Bananas<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'peaches'">Peaches, Nectarines & Plums<br> <br> To select Oranges <a href="javascript:FruitBox(0)">click here</a>.<br> To select Bananas <a href="javascript:FruitBox(1)">click here</a>.<br> To select Peaches <a href="javascript:FruitBox(2)">click here</a>.<br> To read the current value <a href="javascript:alert(window.document.myform.fruit.value)">click here</a>. </form> </body> </html>
Play with the thing a bit. Do you notice a problem? We can select items easy enough using the links, but when we do, the value (as far as javascript is concerned) still comes back as undefined. Interesting.
Javascript Tutor |
Lessons: Intro 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 |
Javascript Authoring Guide JavaScript FAQ |
HTML 4.0 Reference Google Groups (Advanced Search) |
![]() |