Check if a radio button is checked

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Check if a radio button is checked

Post 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?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post 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;
} 
Last edited by VladSun on Tue Aug 07, 2007 4:50 pm, edited 1 time in total.
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

Thanks, I knew that. I was just making sure you did :D
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

LOL :P
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply