mardi 19 mars 2019

When one checkbox is checked in a group, disable & uncheck all other checkboxes

So in the code below, when Report 1 is checked, Report 2 and Report 3 as well as all the options for Report 2 and Report 3 should be un-checked and not selectable. I only want the user to be able to select one report at a time, with the options for that report only to be available for selection. Any assistance is much appreciated.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <form id="myForm">
  <table>
    <tr> <td> <input type='checkbox' name='check1' value = '1'>Report 1    </td> 
         <td> <input type='checkbox' name='check1' value = '2'>R1 Option 1 </td> 
         <td> <input type='checkbox' name='check1' value = '3'>R1 Option 2 </td> 
         <td> <input type='checkbox' name='check1' value = '4'>R1 Option 3 </td> </tr>

    <tr> <td> <input type='checkbox' name='check2' value = '5'>Report 2    </td> 
         <td> <input type='checkbox' name='check2' value = '6'>R2 Option 1 </td> 
         <td> <input type='checkbox' name='check2' value = '7'>R2 Option 2 </td> 
         <td> <input type='checkbox' name='check2' value = '8'>R2 Option 3 </td> </tr>

    <tr> <td> <input type='checkbox' name='check3' value = '5'>Report 3    </td> 
         <td> <input type='checkbox' name='check3' value = '6'>R3 Option 1 </td> 
         <td> <input type='checkbox' name='check3' value = '7'>R3 Option 2 </td> 
         <td> <input type='checkbox' name='check3' value = '8'>R3 Option 3 </td> </tr>
  </table>
  </form>
</body>
</html>

function listen(element, event, callback) {
      if(element.attachEvent) {
        element.attachEvent('on'+event, callback);
      } else {
        element.addEventListener(event, callback);
      }
    }

    var form = document.querySelector('#myForm');
    listen(form, 'click', function(event){
      var checkBoxes, i, checked, target;
      target = event.srcElement || event.target; 
      if(target.getAttribute('name') === 'check1') {
        checkBoxes = form.querySelectorAll('input[name="check2"]');
        checked = target.checked;
        for(i=0;i<checkBoxes.length;i++) {
          checkBoxes[i].disabled = checked && checkBoxes[i] !== target;
        }
      }
    });




Aucun commentaire:

Enregistrer un commentaire