Forum Moderators: open

Message Too Old, No Replies

Validating Radio Buttons

i never noticed...

         

fashezee

2:33 pm on Aug 16, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Using DWMX, I never noticed that I cannot use the validate feature on radio buttons. Is there a way
I can require the user to select a radio button with javascript?

martin

11:23 pm on Aug 16, 2002 (gmt 0)

10+ Year Member



You don't need validation at all.

In a radio buttons group there should be a default, the user can't unselect it, so you don't need to validate.

DrDoc

2:15 pm on Aug 17, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



And, to clearify that even more .. In order for there to be a default, you have to set one. It is easy to do this.

If you're coding for HTML4 you add checked to the tag.
If coding for XHTML1 you add checked="checked" to the tag.

Example: <input type="radio" name="myRadioButton" value="blah" checked>

However, if you do want to validate using JavaScript, you can add a function that checks the value. Therefore, if you have three radio buttons, and the values are blah, shoe, and green .. then, if the second is selected, the value will be shoe.

:)

rewboss

5:48 pm on Aug 17, 2002 (gmt 0)

10+ Year Member



Not quite, DrDoc.

Radio buttons are represented in JavaScript as an array. Each array element is a Radio object. Suppose you have this:


<form name="myform">
<input type="radio" name="fruit" value="banana" checked="checked" />
<input type="radio" name="fruit" value="apple" />
</form>

This will be presented in JavaScript as an array which is accessed as:

document.myform.fruit

This is a normal Array -- it doesn't have a value property.

Each element of the array is a Radio button and each has the following properties:

checked
defaultChecked
value

checked is a boolean and states whether the radio button is checked or not. defaultChecked states whether the radio button has checked="checked" set. And value is the value of the value attribute. So, assuming that the user has selected "apple", the two radio buttons are represented like this:


document.myform.fruit[0].checked == false
document.myform.fruit[0].defaultChecked == true
document.myform.fruit[0].value == 'banana'

document.myform.fruit[1].checked == true
document.myform.fruit[1].defaultChecked == false
document.myform.fruit[1].value == 'apple'

In order to find out the value that will actually be sent to the server, you need to loop through the elements of the array until you find the one with checked==true (there will only be one); then you look up that element's value property. A function to do this might look like this:


function getReturnValue(radioArray){
for(i=0; i<radioArray.length; i++){
if(radioArray[i].checked) return radioArray[i].value;
}
return false;
}

This will return the value of the checked radio button, or false if none is selected (which would probably indicate an error of some sort).