Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select checkboxes with javascript based on html-5 data attribute

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?

Update

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!

like image 507
Brian Powell Avatar asked Mar 31 '15 14:03

Brian Powell


2 Answers

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 />

EDIT

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/

like image 163
Jamie Barker Avatar answered Nov 08 '22 15:11

Jamie Barker


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;
});
like image 45
Pointy Avatar answered Nov 08 '22 14:11

Pointy