This code is not working:
function autoScrub() {
  checkLength = document.querySelectorAll("input[type=checkbox]");
  for (var i=0; i < checkLength.length; i++) {
    if (checkLength[i].attr('data-z') === 1) {
      checkLength[i].checked = true;
    }
  }
}
Each of my checkboxes has a data-z attribute of either 1 or 0.  I'd like to auto-check all of the checkboxes that have a data-z attribute of 1.  The code is breaking at if (checkLength[i].attr('data-z') === 1) { as apparently I cannot read the data-attribute this way.
Apart from this the rest of the code works fine.  I can use checkLength[i].checked = true; and it will check all of the checkboxes, I just can't reference its data-attribute correctly in an if statement and I'm not sure how to.
Any ideas?
I screwed around with two of the solutions below and finally came up with:
function autoScrub() {     
  $("input:checkbox").each(function() {
    if ($(this).data("z") == 0) {      
        $(this).prop('checked', true).trigger('change');                                        
    } 
  }); 
} 
and this worked. Thank you everyone for your help!
in jQuery this is one line of code:
$('input[type="checkbox"][data-z="1"]').prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" data-z="1" /><br />
<input type="checkbox" data-z="0" /><br />
<input type="checkbox" data-z="1" /><br />
<input type="checkbox" data-z="1" /><br />
<input type="checkbox" data-z="0" /><br />
Just noticed a comment about firing the change event:
$('input[type="checkbox"][data-z="1"]').prop('checked', true).trigger('change');
https://api.jquery.com/trigger/
DOM element nodes don't have an .attr() method. I think you're looking for .getAttribute().
if (checkLength[i].getAttribute('data-z') === "1") {
  checkLength[i].checked = true;
}
Also note that your attribute values will be strings, not numbers, so you'll either need to compare to strings as in my edit above, or else compare with ==.
Since you tagged your post with the jQuery tag, I'll add that your code would look like this if you were to go that route:
$("input:checkbox").each(function() {
  if ($(this).data("z") == 1)
    this.checked = true;
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With