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;
   		}
   	}
}

Link to comment
Share on other sites

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;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.