Using JavaScript to write which checkbox is checked

Good day everyone!

I have three checkboxes and a form button.

What I am trying to do is have the checkbox that is checked write a message in a textbox or field.

Example: If a user check box 1 and click the button, the message says “checkbox 1 selected” in the textfield, same for two and three.

I got this to work half way but here is where I am lost.

I am unable to write multiple messages if all three boxes are checked or more than one.

Example: If a user check box 1 and click the button, the message reads in the textfield “Box 1 checked.” If the user check box 2 while box 1 is still checked, the message reads, “box 1 and 2 checked.”

My code is only working for one checkbox at a time.

Here is the JavaScript:

function testCheckBoxes(){
    
var boxChecked = "Checkbox "

for (counter = 0; counter < document.myform.checkbox.length; counter ++){
 
if (document.myform.checkbox[counter].checked == true && boxChecked == "Checkbox "){
    
   boxChecked = boxChecked +document.myform.checkbox[counter].value;
   
   boxChecked ="Checkbox "+ (counter + 1) + " selected";
   
   document.getElementById("textField2").value = boxChecked;
}
}
}

And the HTML:

<form name="myform">


<input type="text" id="textField2" />
<br />
<input type="checkbox" name="checkbox" id="checkbox1" />
<br />
<input type="checkbox" name="checkbox" id="checkbox2"  />
<br />
<input type="checkbox" name="checkbox" id="checkbox2" />
<br />
<input type="button" value="Test Buttons" onClick="testCheckBoxes();" />
</form>

Thanks everyone!

Novice2010

In any solution you will need to attach event listener to those checkboxes. One solution is to remove that button, and to do whatever you doing on that click event, second solution is to keep previous state of checkbox when state is changed and to compare it with current state when you click your button.