June 17, 2015

Javascript validation for radio button.

First write HTML with form and multiple radio fields with same name,

Assign different value for each radio. See in below example.

Also set the form name OR id and form on submit call a function, Below is full example:


<form name="frmAdd" id="frmAdd" onsubmit="return chkRegEvent()" >
  <input type="radio" name="filter" id="filter" value="all" /> View All Evemts
  <input type="radio" name="filter" id="filter" value="upcoming" /> Upcoming Events Only
</form>

In below script check radio button checked OR not?


<script>
function chkRegEvent()
{
    var temp=0;
    for(var i=0; i< document.forms.frmAdd.filter.length;i++)
    {
        if(document.forms.frmAdd.filter[i].checked==true)
        {
            temp=1;
            
        }
        
    }
    if(temp==0)
    {
        alert("Please select filter option.");
        return false;
    }
}
</script>

In alert you should set any message you want.

Enjoy!

No comments:

Post a Comment

Integrating Google reCAPTCHA v3 in HTML Form with PHP

  What is Google reCAPTCHA v3? Google reCAPTCHA is a free service that helps protect websites from spam and abuse. reCAPTCHA v3 is the lates...