Javascript Radios

06Dec10

I’m sure I’ve had to do this many times in my life, and I thought there was an easier way. This is fairly elegant, just passing the name of the radios. (This is basic of the basics.)

function radioSelected(radioGroup){
  for (i = 0; i < radioGroup.length; i++){
    if (radioGroup[i].checked)
        return true;
  }
  return false;
}
if (radioSelected(document.formName.radioButtonName)){

}

I guess a more informative option would be

function getSelectedIndex(radioGroup){
  for (i = 0; i < radioGroup.length; i++){
    if (radioGroup[i].checked)
        return i;
  }
  return -1;
}
if (getSelectedIndex(document.formName.radioButtonName) > 0){

}

And getting the value of the checked item in a radio group

function getSelectedValue(radio) {
  var value = “”;
  if (radio){
    var radioLength = radio.length;
    if(radioLength == undefined){
      if(radio.checked)
        value = radio.value;
    } else {
      for(var i = 0; i < radioLength; i++) {
        if(radio[i].checked)
          value = radio[i].value;
      }
    }
  }
  return value;
}



No Responses Yet to “Javascript Radios”

  1. Leave a Comment

Leave a comment