Change "onclick" into "onchange"

Hi everybody!
I’m running a script, that checks 15 checkboxes in a form and if one is checked it’s name joins a list.

<script>
			document.querySelector('button#listgen').onclick = function () {
				const checkboxes = document.getElementsByName ("items");
				let checkitem = "";
				checkboxes.forEach ((item) => {
					if (item.checked === true) {
						checkitem += item.value + " ";
					}
				})
				if (checkitem === "") {
					document.querySelector('.liste').innerHTML = "";
				} else {
					document.querySelector('.liste').innerHTML = "Items are:  "+checkitem;
				}
			}
		</script>

The script is activated by a button. How must this be changed, that no more “generate”-button is needed and that it works “onchange” (not “onclick”) so that the resulting list is automatically generated depending on which checkbox is checked or unchecked?

Hello, my google search tells me this onchange event works when code loses focus and is related to input not a button etc… My best guess is you may need another script for that.
Also, I found that a function can be Implemented but not sure it is related here.

function getCheckedCheckboxNames() {
 let checkedBoxes = []; 
 
 // Select all checkboxes in the form
 const checkboxes = document.querySelectorAll('form input[type="checkbox"]'); 
 
 // Loop through each checkbox
 for (let checkbox of checkboxes) {
   if (checkbox.checked) {
     // If checkbox is checked, add its name to the list
     checkedBoxes.push(checkbox.name); 
   }
 }
 
 return checkedBoxes; 
}

// Example usage: 
const checkedNames = getCheckedCheckboxNames(); 
console.log(checkedNames); // Will print an array of names of checked checkboxes