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

The Future of Technology: Emerging Trends to Watch in 2025

Introduction As we navigate through 2025, the technological landscape continues to evolve at an unprecedented pace. Innovations that once se...