There is a page:

function handler(e) { var divNode = e.currentTarget.parentNode; // }; var b1 = document.getElementById("b1"); var b2 = document.getElementById("b2"); b1.addEventListener("click", handler); b2.addEventListener("click", handler); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <table id="t1" border="1"> <thead> <tr> <th>Id</th> <th>Name</th> </tr> </thead> <tr> <td>0001</td> <td>СОШ № 2</td> </tr> </table> <button id="b1">+</button> </div> <hr/> <div> <table id="t2" border="1"> <thead> <tr> <th>Id</th> <th>Name</th> </tr> </thead> <tr> <td>0286</td> <td>СОШ № 34</td> </tr> </table> <button id="b2">+</button> </div> 

QUESTION

How to create one handler for two buttons (+), which will add a row to the table for data entry. Initially displayed data (0001 | SOSH № 2) should remain unchanged.

ATTEMPTS

I started writing a handler and, as you can see, I first defined the parent node to find out which of the buttons_ worked. Though kill, but could not execute select of the table.

  • it is enough to find all the nodes you need var buttons = document.querySelectorAll('button') and then hang up the handler through the loop and that's it. - Alexey Shimansky
  • @ Alexey Shimansky, the handler was hanged, and then - how in it (the handler) to find out the button which table worked? - Adam
  • you must have a rigid structure. Each button below each table. Accordingly, the previous sibling (I don’t remember how on js ..... it seems to be e.previousSibling ) is the right table - Alexey Shimansky

2 answers 2

If with jquery , you can do this:

 $(".btn").click(function() { $(this).prev().find("tbody").append('<tr><td><input type="text" /></td><td><input type="text" /></td>') }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <table id="t1" border="1"> <thead> <tr> <th>Id</th> <th>Name</th> </tr> </thead> <tbody> <tr> <td>0001</td> <td>СОШ № 2</td> </tr> </tbody> </table> <button class="btn">+</button> </div> <hr/> <div> <table id="t2" border="1"> <thead> <tr> <th>Id</th> <th>Name</th> </tr> </thead> <tbody> <tr> <td>0286</td> <td>СОШ № 34</td> </tr> </tbody> </table> <button class="btn">+</button> </div> 

    You can simplify everything to understand the essence of what is happening. Let a little crooked. But it will be clear. Write the function handler (), but take some argument. For example, presses the top + let X = 1; clicking another will be X = 2. As a result, you have one handler doing it in one case, otherwise, otherwise)