如何擷取Web頁面中radio按鈕的值

來源:互聯網
上載者:User
如果在web頁面的表單(表單名form1)裡用了一組radio按鈕,起名為button1。
要從js中取得被選中按鈕對應的值,可按以下方法:
<script language=javascript>
function getRadioValue()
{
    var str;
    for(i=0;i<document.form1.button1.length;i++)
    {
        if (document.form1.button1[i].checked)
        str=document.form1.button1[i].value;








    }
}
</script>
這裡的radio名button1就相當一個數組名










相關的例子:
<input type="radio" name="RadioButtn" value="A" checked>One<br><input type="radio" name="RadioButtn" value="B">Two<br><input type="radio" name="RadioButtn" value="C">Three<br><input type="radio" name="RadioButtn" value="D">Four所有的4個選項按鈕對象有同一個名字:RadioButtn,這樣一來,
HTML和JavaScript就知道它們是同一個數組裡的對象。其次,
每個選項的值是選項的別名,並不是看到的文字(例如“One”、“Two”等)。

為了得到選擇的選項的值,首先要知道哪個選項被選中了,然後在alert語句中,
用那個選中的選項的下標值來正確地引用當前選項的值。也就是說,
如果第一個選項被選中,你應該取RadioButtn[0].value,如果第二個選項被選中,
你就應該取RadioButtn[1].value,依此類推。

在JavaScript中,某些類型的域具有selectedIndex屬性,
代表當前選中選項的數組下標值。然而選項按鈕並不是那麼幸運,
同樣,複選框也沒能逃脫厄運。要想得到當前選中的選項按鈕的值,
你必須在RadioButtn數組元素中尋找“checked”屬性。

下面是按鈕的代碼:

var doc = document.forms[0];
for(i = 0; i < doc.RadioButtn.length; i++)
{
 if(doc.RadioButtn[i].checked)
 {
 alert(doc.RadioButtn[i].value);
 break;
 }
}
相關文章的串連:http://www-900.ibm.com/developerWorks/cn/lotus/lo-jsobj/index.shtml

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.