I\'m really bad at Javascript and I\'m struggling to get my head round it.
What I\'m trying to do is get something to select all checkboxes. However everything I have fo
What if you give all of the checkboxes the same name + a number(ie. chkbox1
, chkbox2
,etc...). Then in your javascript you would create a for loop to go through the number of checkboxes you have, and do getElementByID("chkbox" + num)
(where num is your loop variable).
Try this using jQuery:
$(".className").prop("checked", true);
$("#idName").prop("checked", true);
var array = document.getElementsByTagName("input");
for(var ii = 0; ii < array.length; ii++)
{
if(array[ii].type == "checkbox")
{
if(array[ii].className == YOUR_CLASS_NAME)
{
array[ii].checked = true;
}
}
}
by ID:
var checkbox = document.getElementById(YOUR_ID);
if(null != checkbox)
checkbox.checked = true;
I always had a tough time with javascript. You might want to investigate the jQuery javascript library. It's greatly enhanced my ability to solve problems using javascript, as well as create more clear and concise code to manipulate and access the DOM.
With jQuery you should be able to easily select all the checkboxes you'd like by ID and then loop through them setting their value to be checked.
Using JQuery, you can do this very easilly!
$(".ClassName").attr("checked", "true");
or a single ID
$("#ID").attr("checked", "true");
See: Check All Checkboxes with JQuery.
By class:
var clist=document.getElementsByClassName("MyClass");
for (var i = 0; i < clist.length; ++i) { clist[i].checked = "checked"; }
By ID:
var clist=document.getElementById("MyID");
for (var i = 0; i < clist.length; ++i) { clist[i].checked = "checked"; }
See also: Loop Over querySelectorAll Matches.
By class:
$('.myclass:input:checkbox').each(function() { this.checked = true; });
By ID:
$('#myID:input:checkbox').each(function() { this.checked = true; });
Related: How to reset all checkboxes using jQuery or pure JS?