简体   繁体   English

检查是否已选中所有单选按钮

[英]Check if all radio buttons are checked

i want to check some radio buttons to allow the user to click a link (otherway it should appeal a allert). 我想检查一些单选按钮,以允许用户点击一个链接(否则它应该对一个allert上诉)。

here is the code 这是代码

<html>
<head>
</head>
<body>
<a href="http://www.aerosoft.de" id="a_next">aerosoft.de</a>

            <li class="radiobutton"><span class="name">Struct. Temp. Indic.> 38°C -not exceed 55°C</span>
            <input name="1" type="radio" value="other" /></li>
            <li class="radiobutton"><span class="name">Airplane Documents - check </span>
            <input name="2" type="radio" value="other" /></li>
            <li class="radiobutton"><span class="name">Flight Control Lock - removed</span>
            <input name="3" type="radio" value="other" /></li>
</body>
</html>

The user have to check all 3 Radiobuttons to let the link work, otherway if he just have check 2 radiobuttons he should get a alert if he click on the link. 用户必须检查所有3个Radiobuttons以使链接工作,否则,如果他只检查2个radiobutton,他应该在他点击链接时收到警报。

Would be great if someone could help :/ 如果有人可以提供帮助,那会很棒:/

Greets Fabian 向法比安致敬

Handle the click event on the link. 处理链接上的click事件。 Loop through the radios, and if any are not checked display the alert and return false to cancel the click's default action (ie, cancel the navigation). 循环通过无线电,如果没有选中,则显示警报并返回false以取消点击的默认操作(即取消导航)。

window.onload = function() {
    document.getElementById("a_next").onclick = function(e) {
        if (!e) e = window.event;
        var els = document.getElementsByTagName("input"),
            i;
        for (i=0; i < els.length; i++) {
            if (!els[i].checked) {
                alert("Your message here.");
                e.returnValue = false;
                return false;
            }
        }
    };
};

Demo: http://jsfiddle.net/t9wqc/ 演示: http//jsfiddle.net/t9wqc/

If you can use jQuery, its much cleaner.. 如果你可以使用jQuery,它更清洁..

See full example here 在此处查看完整示例

<a href="#">aerosoft.de</a>


var link = "http://www.aerosoft.de" ;

$('input').change(function(){
   var allChecked = $('input:checked').length == 3;

    if(allChecked ){
      $('#a_next').attr('href',link).removeClass('disabled');
    }
    else{
      $('#a_next').attr('href','#').addClass('disabled');
    }             
});​

If you can use jQuery, 如果你可以使用jQuery,

EDITED: (after comments; previous answer has an error) 编辑:(评论后;以前的答案有错误)

$(document).ready(function() {
    $('#a_next').click(function(e){                 
        $('input[type="radio"]').each(function(){
            if(!$(this).prop('checked')) {
               alert('Check all radios first');
               e.preventDefault();  // to stop anchor jumping to url
               return false;      // to break .each
            }
        }); 
    });
});

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM