Free Javascript Tutorials

home

JavaScript Tutorials

Form Validation continued

 
Our quick javascript links
Little Programmes
 
 
 
 
 
 

 

Using JavaScript to Validate Radio Buttons

 

Radio buttons are closely related to check boxes. Only, with a radio button you get just the one choice from a list of options. With a check box you can tick all the boxes, if you wanted. Here's what radio buttons look like on a form:

Your Location:

North East North West South East South West Midlands

If you clicked another option, the one already selected is deselected. Here's the HTML code for our radio buttons:

<Input type = radio Name = r1 Value = "NE">North East
<Input type = radio Name = r1 Value = "NW">North West
<Input type = radio Name = r1 Value = "SE">South East
<Input type = radio Name = r1 Value = "SW">South West
<Input type = radio Name = r1 Value = "midlands">Midlands

Notice that the NAME of all the radio buttons is the same - r1. We use this name in our JavaScript function. Again, we're assuming the NAME of our form is f1. Here's a function which checks which radio button was selected:

function GetSelectedItem() {

chosen = ""
len = document.f1.r1.length

for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}

if (chosen == "") {
alert("No Location Chosen")
}
else {
alert(chosen)
}
}

Again. We're just looping round and checking which item is selected. This time, we're using the checked property of the radio button:

if (document.f1.r1[i].checked)

If a checked item is found, the value of the radio button clicked will be put into our chosen variable:

chosen = document.f1.r1[i].value

Try out the Radio Buttons again. Select an option and see what happens

Your Location:

North East North West South East South West Midlands

 

And with radio buttons tested, we can leave this Form validation section for good. You need never return again, if you don't want to. You can move on the final section of this course - String manipulation.

Move on to the Next Section-->

<--Back to the JavaScript Contents Page