samedi 25 avril 2020

If first checkbox is checked , disable others based on condition

I have a page with a list of checkboxes with values. Each checkbox has data attributes with corresponding values. If the first checkbox is checked , I only want checkboxes whose data attributes are equal to the current checkbox's data attributes to remain selectable whilst all others are disabled.

I have got this working to a degree but if I uncheck any of the valid selected boxes, all the other checkboxes are enabled. I only want all other checkboxes to be enabled if I haven't got any valid ones selected.

HTML

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <label>Number:7967</label>
<input type="checkbox" class="my-check" data-number="7867" data-code="CB45" / >
 <label>Number:3307</label>
<input type="checkbox" class="my-check" data-number="3307" data-code="HUNT1" / >
 <label>Number:3307</label>
<input type="checkbox" class="my-check" data-number="3307" data-code="HUNT1" / >
 <label>Number:5645</label>
<input type="checkbox" class="my-check" data-number="5645" data-code="KLY" / >
</body>
</html>
$(function(){


    $(".my-check").each(function (e, elem) {
            $(elem).on("change", function () {
                var num = $(this).data("number");
                var co = $(this).data("code");
                if ($(this).eq(0).is(':checked')) {

                    $('.my-check:not([data-number=' + num + '])').attr('disabled', true);
                    $('.my-check:not([data-code=' + co + '])').attr('disabled', true);
                } else {
                    $(".my-check").not($(this)).attr('disabled', false);
                }

            });

        })

Sample code here




Aucun commentaire:

Enregistrer un commentaire