【问题标题】:How to detect the radio button's value change without resubmit the form?如何在不重新提交表单的情况下检测单选按钮的值变化?
【发布时间】:2019-01-11 22:08:56
【问题描述】:

我在这里的一个表单中有 2 个单选按钮,

<form action='' method='post' onsubmit='return checkForm(this, event)'>
     <input type = 'radio' name='allow' value='allow' checked>Allow
     <input type='radio' name='allow' value='disallow'>Disallow
</form>

并且在checkForm函数中,有一段代码用来验证用户是否勾选了Disallow按钮,如果是则显示alert强制用户允许,如果不是则返回true。

然而,我发现当我第一次检查Disallow按钮时,标志显示,然后我将其更改为Allow,但仍然有警告标志突然说我应该将选择更改为允许

这是 checkForm 函数:

<script type="text/javascript">
    function checkForm(form, event) {
        var radio  = document.getElementsByName("allow");
        var counter=0;
        for(i=0;i<radio.length;i++){
            if(radio[i].value=="disallow"){
                alert("Please allow the system to get your data!");
                return false;
            }
        }
        return true;    
    }
</script>

有什么想法吗?非常感谢。

【问题讨论】:

标签: javascript html css radio-button forms


【解决方案1】:

我想我发现你的 HTML 代码有问题:

<input type='radio' name='allow' value='disallow' Disallow

这个标签没有关闭,应该是

<input type='radio' name='allow' value='disallow'> Disallow

另外,您使用的是什么版本的 HTML?如果您使用的是 HTML5 或 XHTML Strict,则需要自行关闭:

<input type='radio' name='allow' value='disallow' /> Disallow

【讨论】:

    【解决方案2】:

    您需要检查该选项是否被选中:

    <script type="text/javascript">
    function checkForm(form, event) {
        var radio  = document.getElementsByName("allow");
        var counter=0;
        for(i=0;i<radio.length;i++){
            if(radio[i].checked && radio[i].value=="disallow") {
                alert("Please allow the system to get your data!");
                return false;
            }
        }
        return true;    
    }
    </script>
    

    现代浏览器:

    function checkForm(form, event) {
        if(document.querySelector('input[name="allow"]:checked').value=="disallow") {
            alert("Please allow the system to get your data!");
            return false;
        }
    
        return true;    
    }
    

    【讨论】:

    • 非常感谢您的回复!真的很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2016-08-29
    • 2021-12-20
    相关资源
    最近更新 更多