-2

Problem: I have a page which has multiple save button and an alert message will pop out if the button is pressed.I have a saveAll button which is using nodeList to save all data based on whether the checkbox is checked, meaning if 10 checkbox is checked then the saveall() function will execute the save() function 10 times and 10 alert message will pop out.

What I expected: I want to run the saveAll() function and the alert message should only pop out one time so I am expecting a function to restrict the alert in save() function to execute one time only even though it will be executed 10 times continuously. Any other way to get the expecting result is appreciated.

Example Code:

<table class="table" border="1">
      <thead>
        <tr>
          <th>Input</th>
          <th><input id="1"></th>
          <th><input type="checkbox" class="box"></th>
          <th><button type="submit" onclick="save()">save</button></th>
        </tr>
        <tr>
          <th>Input</th>
          <th><input id="2"></th>
          <th><input type="checkbox"  class="box"></th>
          <th><button onclick="save()">save</button></th>
        </tr>
        <tr>
          <th>Input</th>
          <th><input id="3"></th>
          <th><input type="checkbox"  class="box"></th>
          <th><button onclick="save()">save</button></th>
        </tr>
        <button onclick="saveall()">save all</button>
      </thead>
    </table>

function save(){
    //save something into database
     alert("success");
}
       
function saveall() {
        let nodeList = document.querySelectorAll('.box:checked');
        nodeList.forEach(node => node.parentNode.parentNode.querySelectorAll('button')[0].click());
}  
Anno123
  • 67
  • 6

2 Answers2

0

this is happening due to event bubbling hence stopped using event.stopPropagation.

explained with example in https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing#:~:text=Event%20bubbling%20and%20capturing%20are,the%20elements%20receive%20the%20event.

-1
function saveall(event) {
    let nodeList = document.querySelectorAll('.box:checked');
    nodeList.forEach(node => node.parentNode.parentNode.querySelectorAll('button')[0].click());
    event.stopPropagation();
} 
Tyler2P
  • 2,324
  • 26
  • 22
  • 31