Add Checkbox in HTML Table using JavaScript for Dynamic Selection
In this method, we’ll add a “Select All” checkbox to select or deselect all checkboxes in the table dynamically using JavaScript.
HTML
<!DOCTYPE html> < html > < head > < title >Dynamic Table with Checkboxes</ title > < style > table { margin: auto; } </ style > < script > function toggle(source) { let checkboxes = document .querySelectorAll('input[type="checkbox"]'); for (let i = 0; i < checkboxes.length ; i++) { if (checkboxes[i] != source) checkboxes[i] .checked = source .checked; } } </script> </ head > < body > < table border = "1" > < tr > < th >< input type = "checkbox" onclick = "toggle(this);" ></ th > < th >Name</ th > < th >Email</ th > </ tr > < tr > < td >< input type = "checkbox" name = "select" ></ td > < td >XYZ</ td > < td >xyz@w3wiki.org</ td > </ tr > < tr > < td >< input type = "checkbox" name = "select" ></ td > < td >ABC</ td > < td >abc@w3wiki.org</ td > </ tr > </ table > </ body > </ html > |
Output:
Explanation
- We add a “Select All” checkbox in the header row of the table by inserting an
<input>
element with thetype
attribute set to “checkbox” in the first<th>
element. - We define a JavaScript function
toggle(source)
that takes the “Select All” checkbox as the source parameter. This function iterates over all checkboxes in the table and sets theirchecked
property to match thechecked
property of the source checkbox. - The
onclick
attribute of the “Select All” checkbox is set to call thetoggle(this);
function, passing the checkbox itself as the argument.
How to Add Checkbox in HTML Table ?
Adding checkboxes to an HTML table can be useful for various purposes, such as selecting multiple rows for batch processing or toggling the state of individual items. In this article, we will explore two methods to add checkboxes to an HTML table i.e. using basic HTML and JavaScript for dynamic interaction.
Contact Us