0

I am working on creating a table that I can add and delete rows from it dynamically using JQuery. My problem is that the only delete button that works fine is the first one ( the one with the first default row) later on whenever I add new rows the delete buttons for them doesn't remove the row. These are parts of my code. I will appreciate your help!

 <script>
            $(document).ready(function(){

                $("#add").click(function(){
                    var id="<input type='text' placeholder='Enter student id'>";
                    var name = "<input type='text' placeholder='Enter student name'>";
                    var timeSlot="<input type='text' placeholder='The time slot'>";

                    var row = "<tr> <td>"+id+"</td>" +
                         "<td>"+name+"</td>" + 
                         "<td>"+timeSlot+"</td>"+
                         " <td> <button class='remove' type='submit'>Remove Row</button> </td> </tr>";

                    $("tbody").append(row);
                });

                $("button.remove").click(function(){
                   $(this).parents("tr").remove();
                });
            });
        </script>
<table id="myTble">
            <thead>
                <tr>
                    <th>Student id</th>
                    <th>Student name</th>
                    <th>TimeSlot</th>
                    <th> <button id="add" type="submit">Add Row</button> </th>
                </tr>
            </thead>
              
            <tbody>
                <tr> 
                    <td>00000000</td>
                    <td>xxx xxxxx</td>
                    <td>9:00-10:00</td>
                    <td> <button class="remove" type="submit">Remove Row</button> </td>
                </tr>
            </tbody>

        </table>
  • 1
    Change your click function for delete row to this -> `$(document).on('click', "button.remove", function() { $(this).parents("tr").remove(); });` and read about event binding and on dyanamically added elements - Refer to this question: [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Always Helping Mar 12 '22 at 03:33

0 Answers0