Jump to content

[SOLVED] validating a form with radio buttons that have the same name


mkybell

Recommended Posts

been struggling with this and can't figure it out

 

trying to validate a form with radio buttons

there are 15 elements with 3 radio buttons each (name and id are the same)

if there are any fields where no choice has been made I want an alert message

from what I've read in tutorials you can reference radio buttons with the same name like an array, with brackets

 

I either get an error saying ....has no properties or the whole thing is undefined

 

the only way I get this to work is by using the actual radio button name but I'd like to streamline this with variables and a loop

 

any help is much appreciated, thanks in advance

 

for (i=0;i<15;i++)
{
	var temp = document.getElementById(fields[i])
	if (temp[0].checked==false && temp[1].checked==false && temp[2].checked==false)
	{
		alert(msg[i]+" is required");
		return false
	}
}
return true

Link to comment
Share on other sites

First, you should use the form's elements, not the document's.

 

Second, you can check each element's length properly, which for those of the same name, will be the length of the collection, so you can iterate though those.

Link to comment
Share on other sites

thanks for the tip

I got it working with the following

not as neat as it probably could be but it's fine for me

 

	var j = 0;
for (i=0;i<15;i++)
{
		var ar = j/3;
		if (document.forms[0].elements[j].checked==false && document.forms[0].elements[j+1].checked==false && document.forms[0].elements[j+2].checked==false)
		{
			alert(msg[ar]+" is required.");
			return false
		}
		j+=3;
}
return true

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.