简体   繁体   中英

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).

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.

Would be great if someone could help :/

Greets Fabian

Handle the click event on the link. 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).

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/

If you can use jQuery, its much cleaner..

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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