2011-11-02 32 views
8
<input checked=checked type="radio" name="colors" value="red" />Red 
<input type="radio" name="colors" value="green" />Green 
<input type="radio" name="colors" value="blue" />Blue 

鑑於上述情況,我設置了紅色按鈕默認選擇(所以我給它checked=checked屬性。有了這個,如果我叫.checked即輸入元素上,它總是返回true,即使再選項被選中如何使用純javascript查找單選按鈕的值?

在普通的JavaScript(jQuery的沒有),你怎麼能得到的實際選擇的選項

+0

的可能重複[如何我得到的值一個單選按鈕與JavaScript](http://stackoverflow.com/questions/3778206/how-to-i-get-the-value-of-a-radio-button-with-javascript) –

回答

7

試試這個:

var options = document.getElementsByName("colors"); 
if (options) { 
    for (var i = 0; i < options.length; i++) { 
     if (options[i].checked){ 
      alert(options[i].value); 
     } 
    } 
} 

這麼多使用jQuery容易,但...只是說。

+0

這基本上是我我現在正在做,但正如我所說,.c對於紅色輸入元素,hecked始終返回true,因爲它在創建時顯式設置爲checked = checked,即使自此之後選擇了另一個選項 –

+0

爲什麼默認要檢查的選項? –

+0

在這種情況下,紅色需要默認檢查。有沒有其他的解決辦法呢? –

1

我相信你會發現它的document.all集合中:?

var selectedColor = document.all["colors"]; 
0

那麼,它們都有相同的名稱。所以自然至少要選擇其中一個。給他們不同的ID,然後再試一次。

0

你可以嘗試這樣的.....

這是例如

<form name="frmRadio" method="post"> 
<input name="choice" value="1" type="radio" />1 
<input name="choice" value="2" type="radio" />2 
<input name="choice" value="3" type="radio" />3 
<input name="choice" value="4" type="radio" />4 
</form> 

函數來獲得所選擇的值

<script language="JavaScript"> 

    function getRadioValue() { 
     for (index=0; index < document.frmRadio.choice.length; index++) { 
      if (document.frmRadio.choice[index].checked) { 
       var radioValue = document.frmRadio.choice[index].value; 
       break; 
      } 
     } 
    } 

</script> 
相關問題