Recent Posts

JavaScript Radio Button Validation

Wednesday 20 May 2015


Radio button validation- Radio button and checkbox validation both are almost similar to each other. To validate checkbox you have to write “.checked” property. The same you can apply for checkbox. Radio button returns value ‘true’ if it’s selected, otherwise its returns ‘false’. For radio button validation you don’t need to consider “true” parameter, JavaScript understands this parameter automatically. You can easily get the value of radio button field using their name or using their id. Below is script snap and actual implementation of this script is added. Try it and refer this to customize, accordingly you/ your requirement by changing field name or id name.

Script Snap:
<script> function ValidateRadioButton() { var RdBtn_Object=document.getElementsByName('Loc'); var Flag='No'; for (i=0; i < RdBtn_Object.length; i++) { if (RdBtn_Object[i].checked==true) { alert(' Your selected value is :' +RdBtn_Object[i].value); Flag='Yes'; } } if(Flag=='No') { alert( 'You have not selected any location.'); return false; } } </script> <input type="radio" name="Loc" value="US" > US <input type="radio" name="Loc" value="FRANCE" > FRANCE <input type="radio" name="Loc" value="INDIA" > INDIA <input type="radio" name="Loc" value="UK" > UK <input type="radio" name="Loc" value="CHINA" > CHINA <button onclick="ValidateRadioButton()">Validate Radio Button</button>

Implementation -try it!! ,
US
FRANCE
INDIA
UK
CHINA








Method 2: Validate Radio Button Using 'forms[0].field.value' method
<script> function ValidateRadioButton() { var Rdbtn_Object=document.forms[0].Loc; // Select field using forms[0].field method var Flag='No'; for (i=0; i < Rdbtn_Object.length; i++) { if (Rdbtn_Object[i].checked==true) { alert(' Your selected value is :' +Rdbtn_Object[i].value); Flag='Yes'; } } if(Flag=='No') { alert( 'You have not selected any location.'); return false; } } </script> <form name="form" method="post"> <input type="radio" name="Loc" value="US" > US <input type="radio" name="Loc" value="FRANCE" > FRANCE <input type="radio" name="Loc" value="INDIA" > INDIA <input type="radio" name="Loc" value="UK" > UK <input type="radio" name="Loc" value="CHINA" > CHINA <button onclick="ValidateRadioButton()">Validate Radio Button</button> </form>



Implementation -try it !
US FRANCE INDIA UK CHINA
Note : This method will return Error 405, As we are using FORM submit method, this error will not occur for your application.








No comments:

Post a Comment

 

Blogger JavaScript

Contact Us

Name

Email *

Message *

Tutorials