14 Jan, 2004
Radio Button – Changing selection (checked) and focus
Posted by: Jennifer In: Script snippet
Just some snippets for safe keeping regarding radio buttons. One that will change which radio button is selected. The other that will change the focus to the appropriate radio button (useful when validating that fields are filled out in a form)
To change which radio button is selected
Lets say you want to change which radio button is selected if someone starts typing into a text field. So, within the tag of the text field, using the onClick event, you call a javascript function which checks to see if there's anything in the text field, and if so, change which radio button is "checked". (this is basically where I found it)
Here's the function:
function checkField() {
if(document.FORMNAME.TEXTFIELDNAME.value != "")
document.FORMNAME.RADIOGROUP[3].checked = true;
}
(basically you're looking at the radio group as an array. [0] is for the first radiobutton in that group that appear, [1] is for the second, and so on.
That text field that calls the function:
<input type="text" name="TEXTFIELDNAME" onClick="checkField()">
Change Focus to a radio button:
When I use javascript to validate a page, I will change focus to the field that requires attention before the form can be submitted. (this is basically where I found this code). So after you check to make sure they made a radio button selection (see the javascript validation post for how to do that) if there was no selection made, after you throw the "alert" message, you can send the focus to the radio button: