JavaScript如何取得Radio被選中的值

來源:互聯網
上載者:User

一般使用遍曆的方法,判斷每個Radio是否被選中,如果是,再取其值.

<form id="userlist" method="post" action="option.php">
 <input type="radio" name="userid" value="1">1
 <input type="radio" name="userid" value="2">2
 <input type="radio" name="userid" value="3">3
 </form>

<script language="javascript">
 function usubmit(action){
 var radionum = document.getElementById("userlist").userid;
 for(var i=0;i<radionum.length;i++){
 if(radionum[i].checked){
 userid = radionum[i].value
 }
 }
 window.location.href='option.php?action='+action+'&userid='+userid;
 }
 </script>

這裡有兩個要注意的地方:一個是如何取值,一個是如何遍曆
document.getElementById("userlist").userid;
這是根據form的id再取其中控制項元素的name取值的方法。
也可以用document.getElementsByName("userid")直接獲得

getElementById與getElementsByName的區別,getElementById取radio類型元素只能選取單個控制項,getElementsByName取radio類型元素的時候是取出的整個radio數組,如果一定要用getElementById,則可像上面代碼一樣先用getElementById取得整個表單的id.後面緊跟radio名稱即可

現在知道document.getElementsByName("userid")就是得到一個數組,該數組中的元素是該dom樹中所有name為radionum的元素,即使只有一個radio,也是一個只包含一個元素的數組.
而document.all.userid則不同,它是得到頁面中的userid元素的引用,當頁面中存在多個radio時,它返回的是一個數組,如果頁面中只包含一個radio,則得到的就是這個radio對象的引用.由於這時得到的不是一個數組,因此就不能遍曆數組來進行判斷了.

 

做成函數吧,如下:

function   getRadioBoxValue(radioName)
  {
            var obj = document.getElementsByName(radioName);             //這個是以標籤的name來取控制項
                 for(i=0; i<obj.length;i++)    {

                  if(obj[i].checked)    {
                          return   obj[i].value;
                  }
              }        
             return "undefined";      
  } 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.