Monday, March 26, 2012

Check Radio Button State

If you have radio buttons and one of the buttons is checked by default, you may need to check if the buttons state has been changed, and only then proceed with form submission. Suppose you have a group of radio buttons named 'cities':
<input type="radio" name="cities" value="Paris"> Paris<br>
<input type="radio" name="cities" value="London" checked> London<br>
<input type="radio" name="cities" value="Berlin">Berlin<br>
Here is a JavaScript function that will return true if a radio button value has been changed, and false if not. We assumed that the form name is frm1.
function checkRadioButtons(){
 var rr = document.frm1.cities;
 var len = rr.length;
 while(len-->0){
  if(rr[len].checked !=rr[len].defaultChecked)
   return true;
 }
 return false;
}
Radio buttons and checkboxes have a defaultChecked property which reflects the initial state of an element's checked attribute. The code loops through each radio button and checks whether the current checked property is equal to the defaultChecked property of an element, in which case it means that the element state has been changed.
This function is called on form submit as follows: 'return checkRadioButtons()'. If the function returns true, the form submission takes place. If the function returns false, nothing happens.

1 comment: