JavaScript如何正確讀取Radio的值

來源:互聯網
上載者:User

     Radio 是 HTML 中的單選框,同一個 form 中,name 相同的 Radio 構成一組,這一組中最多隻允許有一個 Radio 被選中。

     如果將 form 提交到伺服器端 ASP 程式,ASP 程式要獲得使用者選擇的那個 Radio 的 value 是非常方便的,用 request.Form("RadioName"),不必理會有幾個 Radio。

     但在 JS(JavaScript) 中就要複雜多了,我們不能像對其它元素(如:文字框)一樣,使用 formid.objName.value 來取值,我們應該迴圈這個組的 Radio,判斷其 checked 屬性,再取值。

 

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>讀取 Radio 的值</title>
</head>

<body>

<form id="form1" action="" method="">
    <div><input type="radio" name="r" id="r1" value="一"><label for="r1">選項一</label></div>
    <div><input type="radio" name="r" id="r2" value="二"><label for="r2">選項二</label></div>
    <div><input type="radio" name="r" id="r3" value="三"><label for="r3">選項三</label></div>
    <div><input type="button" value="檢查選擇項" onclick="javascript:Foo();"></div>
</form>

<script type="text/javascript" language="javascript">...
<!--
function Foo()
...{
    var selectedIndex = -1;
    var form1 = document.getElementById("form1");
    var i = 0;
    
    for (i=0; i<form1.r.length; i++)
    ...{
        if (form1.r[i].checked)
        ...{
            selectedIndex = i;
            alert("您選擇項的 value 是:" + form1.r[i].value);
            break;
        }
    }
    
    if (selectedIndex < 0)
    ...{
        alert("您沒有選擇任何項");
    }
}
-->
</script>

</body>

</html>

 

     阿磊記:

          其中 擷取form 這步很重要,一定要通過document.getElementById 取得,如果直接使用document.form1貌似後面的radiobox 沒有辦法取得 實在搞不懂為什麼

相關文章

聯繫我們

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