Page 1 of 1

Check if a radio button is checked

Posted: Tue Aug 07, 2007 7:35 am
by shiznatix
Ok so I want to make sure that at least 1 radio button is selected before the form is submitted. I have this javascript going on:

Code: Select all

function deny_user(email_id)
{
	window.opener.document.location.href = "website_url/?_action=deny&email_id="+email_id+"&show=confirmed";

	window.opener = self;
	window.close();
}

function get_radio_value()
{
	for (var i = 0; i < document.email_form.id.length; i++)
	{
		if (document.email_form.id[i].checked)
		{
			deny_user(document.email_form.id[i].value);
			return true;
		}
	}

	alert("You must select a type of email");
	return false;
}
And I have this HTML form:

Code: Select all

		
<form name="email_form">
	<table class="small-table" border="1">
		<tr>
			<td>Invalid Username</td>
			<td>
				<input type="radio" name="id" value="28"/>
			</td>
		</tr>
		<tr>

			<td colspan="2" style="text-align: right;">
				<input type="submit" onclick="return get_radio_value();" value="SEND"/>
			</td>
		</tr>
	</table>
</form>
Now everything goes perfectly unless there is only 1 radio button. If there is only 1 button then it will never let me submit it. Can someone lend me a hand and tell me why this problem exists?

Posted: Tue Aug 07, 2007 7:44 am
by VladSun
Because in one radio button case variable id is not an array.

Code: Select all

function get_radio_value()
{
	if (document.email_form.id.length)
	{
               for (var i = 0; i < document.email_form.id.length; i++)
               {
                      if (document.email_form.id[i].checked)
                      {
                                deny_user(document.email_form.id[i].value);
                                return true;
                      }
               }
	}
	else
	{
		if (document.email_form.id.checked)
		{
				deny_user(document.email_form.id.value);
				return true;
		}
	}
	alert("You must select a type of email");
	return false;
} 

Posted: Tue Aug 07, 2007 8:00 am
by shiznatix
Thanks, I knew that. I was just making sure you did :D

Posted: Tue Aug 07, 2007 8:04 am
by VladSun
LOL :P