简体   繁体   中英

check if 1 of 2 check boxes per group is checked on form submit?

I have 8 check boxes, split into groups of 2. in the first group, I have one checkbox labeled checkbox1 and one labeled checkbox2. I want a JavaScript code that will allow me to be able to check on the form submit whether at least one of 2 of these checkboxes has been checked for each group.

I do not want a script that simply checks to see if you have checked only one checkbox as this will mean the user would not have to check at least one of the other checkboxes in the other group of checkboxes.

Does anyone know of a way of how I can do this please and am I going along the right lines?

$('#form_check').on('submit', function (e) {
  if ($("input[id=box1]:checked").length === 0) {
    if ($("input[id=box2]:checked").length === 1) {

    } else {
      if ($("input[id=box2]:checked").length === 0) {
        if ($("input[id=box1]:checked").length === 1) {    
          e.preventDefault();
          alert('no way you submit it without checking a box');
          return false;
        }
      }
    }
  }
});

Do it like this:

$("button").click(function(){
    var length = 0;  // initial length 

    $(".group").each(function(){ 
        // if box is checked, add 1, else 0
        length += ($(this).find("input:checked").length === 1);
    });

    // if there are as many box's checked as many groups, i.e. one checked box per group
    if(length === $(".group").length){
        alert("y");
    }else{
        alert("no");
    }
});

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