'jQuery checkboxes - explanation
I had made a small form with no. of checkboxes... When I click on "Check all"-checkbox, then all the checkboxes are checked automatically. This is my code, but I have taken the following code from the internet only. Although it's working but as I am new to jQuery, I don't understand what this code does. Can someone please explain?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
alert("Yoy have checked all");
});
});
</script>
</head>
<body>
<form>
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
<fieldset>
<legend>All Checkboxes</legend>
<p><label><input type="checkbox" /> Option 1</label></p>
<p><label><input type="checkbox" /> Option 2</label></p>
<p><label><input type="checkbox" /> Option 3</label></p>
<p><label><input type="checkbox" /> Option 4</label></p>
</fieldset>
</form>
</body>
</html>
Solution 1:[1]
Here is script with comments:
// When document is ready, run function
$(document).ready(function(){
// When 'change' event is triggered on element with id 'checkAll'
// run function
$("#checkAll").change(function () {
// Set property 'checked' of all inputs with type 'checkbox'
// to state that #checkAll input has
$("input:checkbox").prop('checked', $(this).prop("checked"));
// Alert 'Yoy have checked all'
alert("Yoy have checked all");
});
});
You can see it in action here.
If you are not very familiar with jQuery or JavaScript, please check some beginner tutorials on YouTube or just Google it. There are plenty of video tutorials that explain basic HTML and jQuery stuff which should be very useful.
Note that stackoverflow is not a place where other developers will explain what some snippet of code does.
Hope this was useful :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bulicmatko |
