使用JavaScript验证单选按钮

时间:2013-09-06 06:54:18

标签: php javascript html

我正在尝试按照本网站上的教程指南http://homepage.ntlworld.com/kayseycarvey/jss3p11.html

但是,这样做时我遇到了一些困难。 即使我做了完全相同的事情。如果你知道,请指导我。 以下是我的所作所为:

<html>
    <script>
        function GetSelectedItem() {

            chosen = ""
            len = document.f1.r1.length

            for (i = 0; i <len; i++) {
                if (document.f1.r1[i].checked) {
                    chosen = document.f1.r1[i].value
                }
            }

            if (chosen == "") {
                alert("No Location Chosen")
            }
            else {
                alert(chosen) 
            }
        }
    </script>

    <body>
        <form name="f1">
        <Input type = radio Name = r1 Value = "NE">North East
        <Input type = radio Name = r1 Value = "NW">North West
        <Input type = radio Name = r1 Value = "SE">South East
        <Input type = radio Name = r1 Value = "SW">South West
        <Input type = radio Name = r1 Value = "midlands">Midlands
        </form>


    </body></script>
</html>

在旁注中,我是否必须对表单执行任何操作才能触发GetSelectedItem函数? 提前谢谢!

4 个答案:

答案 0 :(得分:0)

onsubmit="javascript:GetSelectedItem();"添加到您的form代码。

答案 1 :(得分:0)

在单选按钮的onchange事件上添加GetSelectedItem()函数

     <input type="radio" onclick="GetSelectedItem()" value="NE" name="r1">

答案 2 :(得分:0)

window.addEventListener('load', function () {
for (var i = 0; i < document.f1.r1.length; i++) {
    document.f1.r1[i].addEventListener("click", GetSelectedItem);
}
}, false);

function GetSelectedItem() {
alert(this.value);
}

http://jsfiddle.net/udSbL/2/

答案 3 :(得分:0)

试试这个

<input type="radio" onclick="autosubmit(this.value)" value="NE" name="r1">
<script type="text/javascript">
function autosubmit(value) {
window.location='update.php?radiovalue='+value;
}
</script>

update.php

$rbtn=$_GET['radiovalue'];

//here your update query