2008-10-02 59 views

回答

10
<html> 
    <head> 
    <script type="text/javascript"> 
     function testR(){ 
     var x = document.getElementsByName('r') 
     for(var k=0;k<x.length;k++) 
      if(x[k].checked){ 
      alert('Option selected: ' + x[k].value) 
      } 

     } 
    </script> 
    </head> 
    <body> 
    <form> 
     <input type="radio" id="r1" name="r" value="1">Yes</input> 
     <input type="radio" id="r2" name="r" value="2">No</input> 
     <input type="radio" id="r3" name="r" value="3">Don't Know</input> 
     <br/> 
     <input type="button" name="check" value="Test" onclick="testR()"/> 
    </form> 
    </body> 
</html> 
2

如果您需要的實際元素,而不僅僅是選擇的值,試試這個:

function findSelected(){ 
    for (i=0;i<document.formname.radioname.length;i++){ 
    if (document.formname.radioname[i].checked){ 
     return document.formname.radioname[i]; 
    } 
    } 
} 
0

泛型函數(鬆散的基礎上你的)

function getRadioGroupSelectedElement(radioGroupName) { 

    var radioGroup = document.getElementsByName(radioGroupName); 
    var radioElement = radioGroup.length - 1; 
    for(radioElement; radioElement >= 0; radioElement--) { 
     if(radioGroup[radioElement].checked){ 
      return radioGroup[radioElement]; 
     } 
    } 
    return false; 
} 



function getRadioGroupSelectedValue(radioGroupName) { 

    var selectedRadio = getRadioGroupSelectedElement(radioGroupName); 
    if (selectedRadio !== false) { 
     return selectedRadio.value; 
    } 
    return false; 
} 
相關問題