Jump to content

How to use javascript to check if at least one radio button is selected?


ghurty

Recommended Posts

what code to I use to check to make sure at least one of a radio button group is selected?

 

I am using the following code to check if at least one of three text boxes are filled out. But how do I check for a radio button select:

 

if(document.degorderform.txtHomephone.value.length <1 || !document.degorderform.txtHomephone.value.match(/[^s]/))
{
	if(document.degorderform.txtOfficePhone.value.length <1 || !document.degorderform.txtOfficePhone.value.match(/[^s]/))
	{
		if(document.degorderform.txtCellPhoe.value.length <1 || !document.degorderform.txtCellPhoe.value.match(/[^s]/))
		{
			alert("Please enter atleast one phone no.");
			document.degorderform.txtHomephone.focus();
	 		isvalid =  false;
   			return isvalid;
   		}
   	}
}

The following function will return the value of the selected or will return false if none of the values are selected

 

function radioGroupValue(groupObj)
{
    //Check if radio group is an array (i.e. has multiple options)
    if (!groupObj.length)
    {
        //Only one option in group
        return (groupObj.checked) ? groupObj.value : false;
    }

    //Multiple options, iterate through each option
    for (var i=0; i<groupObj.length; i++)
    {
        //Check if option is checked
        if (groupObj[i].checked)
        {
            //Return value of the checked radio button
            return groupObj[i].value;
        }
    }

    //No option was selected
    return false;
}

 

Just pass the radio button object to the function, such as:

if (radioGroupValue(document.formName[radioGroupName])==false)
{
    alert("You must select a value");
    return false;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.