mercredi 22 novembre 2017

Making this jquery bulk checkbox ticker more generic

I have created a JQuery routine to check all the checkboxes on a page using a master checkbox.

I am generally happy with this function and it is serving me well but it is not very generic and I have now copy/pasted it into a number of pages in my solution.

I also have a couple of pages where I have copy/pasted it twice because I have two groups of checkboxes on one page that need to be controlled independently. This is not good!

I would really love to genericise this and stuff it away in my main .js script file but I do not know where to start! I would love to be able to use a system of classes to tell JQuery which set of checkboxes is controlled by which master checkbox.

Can you help please? I feel that a solution would boost my jquery ability massively!

(n.b. please excuse the classes in tags, that is down to the nasty way that asp.net renders checkboxes)

$(function () {
  $(".checkAllLeft").click(function () {
    if ($(".checkAllLeft").is(':checked')) {
      $(".LeftCheckbox").each(function () {
        var checkbox = $(this).find("input")
        if (checkbox.prop("disabled") == false) { checkbox.prop("checked", true); }
      });

    } else {
      $(".LeftCheckbox").each(function () {
        var checkbox = $(this).find("input")
        if (checkbox.prop("disabled") == false) { checkbox.prop("checked", false); }
      });
    }
  });
});

$(function () {
  $(".checkAllRight").click(function () {
    if ($(".checkAllRight").is(':checked')) {
      $(".RightCheckbox").each(function () {
        var checkbox = $(this).find("input")
        if (checkbox.prop("disabled") == false) { checkbox.prop("checked", true); }
      });

    } else {
      $(".RightCheckbox").each(function () {
        var checkbox = $(this).find("input")
        if (checkbox.prop("disabled") == false) { checkbox.prop("checked", false); }
      });
    }
  });
});
<body>
  <script src="http://ift.tt/1yCEpkO"></script>
  <table border=1>
  <tr>
   <td>
      Left<br />
      <input type="checkbox" class="checkAllLeft">
      <br />
      <br />
      <span class="LeftCheckbox"><input type="checkbox" ></span>
      <span class="LeftCheckbox"><input type="checkbox" ></span>
      <span class="LeftCheckbox"><input type="checkbox" ></span>
   </td> 
   <td>
      Right<br />
      <input type="checkbox" class="checkAllRight">
      <br />
      <br />
      <span class="RightCheckbox"><input type="checkbox" ></span>
      <span class="RightCheckbox"><input type="checkbox" ></span>
      <span class="RightCheckbox"><input type="checkbox" ></span>
   </td> 
  </tr>
  </table>
</body>



Aucun commentaire:

Enregistrer un commentaire