Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
My div has many checkboxes,I use
JavaScript
document.getElementById("foodDiv").getElementsByTagName("input")
can get all the checkboxes,but I use
JavaScript
document.getElementById("foodDiv").getElementsByTagName("input").prop('checked', true)
seems not work.
Posted

try this..

JavaScript
$('#foodDiv input[type="checkbox"]').prop("checked", true);
 
Share this answer
 
See my demo code and adapt:
XML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
   $("#checkAll").click(function(){
      alert(this.id);
      $('input:checkbox').not(this).prop('checked', this.checked);
   });
});
</script>

</style>
</head>
<body>

<div id="checkboxes">
    <input id="chkbx_0" type="checkbox"  />Option 1
    <input id="chkbx_1" type="checkbox"  />Option 2
    <input id="chkbx_2" type="checkbox"  />Option 3
    <input id="chkbx_3" type="checkbox"  />Option 4
</div>
<br><br>
<input id="checkAll" type="checkbox" />Check All

</body>
</html>

This is to answer your follow-up query. It means 'excluding this', and what is 'this'? I have included a new line of alert code above, run it to find out the answer. In this case, it is ok to remove the 'not(this)'. And there are usually more than one way to write a program to meet a requirement.
 
Share this answer
 
v7
Comments
vaeaze 4-Jan-14 4:13am    
$('input:checkbox').not(this).prop('checked', this.checked);?Can I ask why do you use not(this)?
$('#foodDiv input[type="checkbox"]').prop("checked", true); is OK like the solution 3.
Peter Leow 4-Jan-14 5:52am    
It means 'excluding this', and what is 'this'? I have included a line of code above, run it to find out the answer.
In this case, it is ok to remove the 'not(this)'.
And there are usually more than one way to write a program to serve a requirement.
You have mentioned jQuery also as on your Tags.So try is as below.

$('#foodDiv').find('input:checkbox').each(function () {

                    $(this).prop('checked', true);

                });
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900