Javascript validation for radio button in HTML form

HTML is having INPUT tag withradio 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 keeep this radio value selection as mandatory we can use this javascript

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

 }
Posted in Javascript Tagged with: ,