Thursday, April 30, 2009

Javascript validation for radio button in HTML form



HTML is having INPUT tag with radio as type to display radio button in the HTML form.

Multiple input tags should be given same name to make it one group.

Consider below code which will allow the user to select any one of 3 topics.

<form>
<input type="radio" name="topicname"/>topic1

<input type="radio" name="topicname"/>topic2

<input type="radio" name="topicname"/>topic3
</form>


If you want to keep this radio value selection as mandatory (i-e topic should be selected before submitting the form), you can use below javascript function.

function validation(myform)
{
var myOption = -1;
for (i=myform.topicname.length-1; i > -1; i--)
{
if (myform.topicname[i].checked)
{
myOption = i;
i = -1;
}
}
if (myOption == -1)
{
alert("You must select a Topic");
return false;
}
}


More Articles...

No comments:



Thanks for visiting our blog


twitterrss facebook linkedin YouTube subscribe


Subscribe via email

Enter your email address: