Thursday, November 18, 2010

How to check a radio button list is checked or not using javascript?

How to check a radio button list is checked or not using javascript ?


Radio Buttons are work in groups .If we have a set of radio buttons on a form , they are unchecked by default. We want an alert message if the radio buttons are not checked on submit.

Radio buttons are stored as an array, so we have to loop the array elements to see if one is checked or not.

To determine whether a particular button is pressed the syntax required is:
test = document.formName.radioGroupName[indexNumber].checked;

This will result a TRUE or False value . If the radio button is checked it will result a TRUE value, otherwise FALSE.

Sample Code

<script language="javascript">

function validate()

{

var flag = false;

for(var i =0 ;i<document.frmgraph.cond1.length; i++)

{

if(document.frmgraph.cond1[i].checked)

flag = true;

}

if(flag == false)

{

alert("Please select the group");

return false;

}

return true;

}

</script>

<form id="frmgraph" name="frmgraph" method="post" onsubmit="return validate();">

Male <input type="radio" name="cond1" id="cond1" value="male" />

Female <input type="radio" name="cond1" id="cond1" value="female" />

<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />

</form>



In this function the javascript will alert a message if the radio button is not checked.

No comments:

Post a Comment