Reputation: 896
I have multiple checkboxes that are created using for loops with Javascript only once the web page has loaded.
I want to make all the checkboxes set to true by default, I can do this in the console, but when I put it in my script, it doesn't work since the function probably loads before the DOM elements have loaded.
I've tried two different approaches, and neither seem to work. In both cases, they only work for the hardcoded checkboxes I typed up (not generated by for loops/DOM). If anyone knows how I can resolve this, I'd be very grateful!
Here is my basic jQuery/JS code.
$(document).ready(function() {
var setTrue = document.getElementsByTagName("input");
for (var i = 0; i < setTrue.length; i++) {
setTrue[i].checked = true;
};
});
$(window).on("load", function() {
var setTrue = document.getElementsByTagName("input");
for (var i = 0; i < setTrue.length; i++) {
setTrue[i].checked = true;
};
});
Upvotes: 0
Views: 86
Reputation: 1147
You can use this example which sets the attribute of all checkboxes on the current page to checked.
$(function(){
$('input:checkbox').prop('checked', true)
})
Upvotes: 2
Reputation: 815
It looks like you got the right way to do it from the comments, which is to change the javascript that adds the checkboxes to just add them with a checked property initially. But for others that are looking to do something similar, where they don't have control over the checkboxes, your jQuery function works, but can be done much more simply like this:
$(document).ready() {
$('input:checkbox').attr('checked', true)
}
jQuery will already do the looping through the input objects for you (and in your attempt, you would end up adding 'checked' to every input, not just checkboxes).
Upvotes: 1