如何取消选中单选按钮

Mor*_*har 0 html javascript radio-button

我想uncheck一个radiobutton我发现了一个方式做这个,但同时单选按钮的表单中的代码将无法正常工作,这是我的脚本为unchecking选中的单选按钮

<script type="text/javascript">
       var allRadios = document.getElementsByName(1);
        var booRadio;
        var x = 0;
        for(x = 0; x < allRadios.length; x++){

            allRadios[x].onclick = function() {
               if(booRadio == this){
                   this.checked = false;
                    booRadio = null;
               }else{
                    booRadio = this;
                }
           }
        }
    </script>

    <form name="theForm" target="_blank" action="laravel.php">
    <label for="test">test</label>
    <input type="radio" id="1" class="radio" name="1" value="1">
    <input type="radio" id="2" class="radio" name="1" value="2">
    <input type="radio" id="3" class="radio" name="1" value="3">
    <input type="radio" id="4" class="radio" name="1" value="4">
    </form>
Run Code Online (Sandbox Code Playgroud)

当单选按钮在表单标签之外时,脚本工作正常,但当无线电输入在表单中时,它无法工作我想知道我在这里缺少什么

wvd*_*vdz 5

问题是订单.你在html完成之前加载你的javascript.

要解决此问题,只需将javascript放在文件末尾附近,就在结束</body>标记之前.

如果你使用jquery,你也可以用它包装$(document).ready(function() { ... }.

  • 正如popovitsj建议的那样,你至少应该在你的表格之后放置你的脚本.如果您正在使用JQuery,那么您还可以考虑将整个脚本包装在$(document).ready()中 (2认同)