Reputation: 45
How would I go about making a javascript for a button to select and deselect all checkboxes?
Checkbox HTML (they all look the same with a different value):
<input type="checkbox" name="moviebox[]" value="Zombieland" style="width: 15px; height: 15px; margin: 0px;">
My button:
<input type="button" value="Select All/None">
Upvotes: 1
Views: 1166
Reputation: 404
<input type="checkbox" name="movieboxes" style="width: 15px; height: 15px; margin: 0px;"/> Zombieland<br/>
<input type="button" onClick="toggleMovieBoxes()" value="Select All/None">
Your entire html file should look like this:
<html>
<head>
<script language="JavaScript">
function toggleMovieBoxes(){
var movie_cbs = document.getElementsByName('movieboxes');
for (var i=0, n=movie_cbs.length;i<n;i++) {
movie_cbs[i].checked = !movie_cbs[i].checked;
}
}
</script>
</head>
<body>
<input type="checkbox" name="movieboxes" style="width: 15px; height: 15px; margin: 0px;"/> Zombieland<br/>
<input type="checkbox" name="movieboxes" style="width: 15px; height: 15px; margin: 0px;"/> Zombieland 2<br/>
<input type="button" onClick="toggleMovieBoxes()" value="Select All/None">
</body>
</html>
Edit:
Added a variable so all the checkboxes will be synced according to its value, also added a tiny touch so the user know better that this is a toggle button and it does something different everytime.
var is_checked = false;
function toggleMovieBoxes(){
var movie_cbs = document.getElementsByName('movieboxes');
var button = document.getElementById('btn');
is_checked = !is_checked;
if(is_checked)
button.value = "Deselect all";
else
button.value = "Select all";
for (var i=0, n=movie_cbs.length;i<n;i++) {
movie_cbs[i].checked = is_checked;
}
}
Upvotes: 0
Reputation: 1003
Add a click event listener to your button and then toggle all the checkboxes when it's clicked.
const button = document.querySelector(".select-all");
const checkboxes = document.querySelectorAll("input[type='checkbox']");
let everythingChecked;
button.addEventListener("click", () => {
checkboxes.forEach(checkbox => {
checkbox.checked = everythingChecked ? false : true;
});
everythingChecked = !everythingChecked
});
<input type="checkbox" name="foo">
<input type="checkbox" name="bar">
<input type="checkbox" name="baz">
<button type="button" class="select-all">
Button
</button>
Upvotes: 1