Sunday, October 7, 2012

manipulating checkboxes in jQuery

Here is some interesting code I wrote in helping a friend today:

<script src="/Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
   jQuery(document).ready(function () {
      $('input[type=checkbox]').bind('click', function () {
         if ($(this).is(':checked')) {var currentId = $(this).attr('id');
            currentId = currentId.substring(11, currentId.length);
            currentId = currentId.substring(0, currentId.length - 8);
            var divId = "tvAppUsersn" + currentId + "Nodes";
            if ($('#' + divId).length != 0) {
               var childcheckboxes = new Array();
               inputuserfields = $('#' + divId + " :input");
               $.each(inputuserfields, function () {
                  $(this).attr('checked', 'checked');
               });
            }
         }
      });
   });
</script>

 
 

Worth mentioning:

  1. This would find immediate children and not the children of children:
    inputuserfields = $('#' + divId + " > :input");
     
  2. I wonder if this would have been checkbox specific (instead of assuming all inputs in a collection were checkboxes):
    inputuserfields = $('#' + divId + " :input[type=checkbox]");
     
  3. This removes a check from a checkbox:
    $(this).removeAttr('checked');

 
 

Addendum 1/17/2019: You might want to use .prop instead of .is in modern jQuery. I'm not positive.

No comments:

Post a Comment