My code is as follows with a nested EventListener:
<!DOCTYPE html>
<html>
<div>Message: <input id="box" /></div>
<button id="okay">Okay</button>
<form>
<div id="rows">
<div>Row 1: <input class="row" id="rowtext[0]" name="row[0]" readonly> <button type="button" id="input[0]" class="activate_row">Activate Row</button></div>
<div>Row 2: <input class="row" id="rowtext[1]" name="row[1]" readonly> <button type="button" id="input[1]" class="activate_row">Activate Row</button></div>
<div>Row 3: <input class="row" id="rowtext[2]" name="row[2]" readonly> <button type="button" id="input[2]" class="activate_row">Activate Row</button></div>
<div>Row 4: <input class="row" id="rowtext[3]" name="row[3]" readonly> <button type="button" id="input[3]" class="activate_row">Activate Row</button></div>
<div>Row 5: <input class="row" id="rowtext[4]" name="row[4]" readonly> <button type="button" id="input[4]" class="activate_row">Activate Row</button></div>
</div>
<div>
Activated Row (for debugging): <input id="activated" name="activated">
</div>
</form>
<script>
var rows = document.getElementsByClassName("row");
var activatebuttons= document.getElementsByClassName("activate_row");
for (var i = 0; i < activatebuttons.length; i++){
activatebuttons[i].addEventListener('click', function(){
var idnum = this.id.slice(6,-1);
var box = document.getElementById("box")
var rowText = document.getElementById("rowtext[" + idnum + "]");
document.getElementById("activated").value = idnum;
box.value = rowText.value;
document.getElementById("okay").addEventListener('click', function(){
alert("ID (for debugging): " + idnum);
rowText.value = box.value;
});
});
}
</script>
</html>
Steps to reproduce the problem:
- Click on a "Activate Row" button to activate a particular row.
- Type a message in the Message box
- Press Okay
- The message should get copied to the appropriate row
This works fine the first time. However, each time I click on one of the "Activate Row" buttons, whether it is the same one or a different one, it seems to add an additional event listener to the "Okay" button. This can be seen with the "alert" I used for debugging.
The problem is that my message gets copied to every row that had previously been activated rather than only the currently activated row. Why is this happening and what can I do to fix it?
To clarify: What I want to happen is for the message to only get copied to the row that was activated. Not to all rows that had previously been activated.