Adding a button input and deleting non-functional parent elements

Here is a simple append function using jQuery, and it's working perfectly.

However, the issue arises when I try to append a button and remove the parent tr upon clicking. The problem lies in using remove parent, as it doesn't seem to work as expected.

The function works fine if the button already exists on the page. However, when I dynamically add a new one using the add button function, the removal process does not function correctly.

$(document).ready(function() {
    $(".add-row").click(function() {
        var name = $("#name").val();
        var email = $("#email").val();
        var markup = `
              <tr>
                  <td>` + name + `</td>
                  <td>` + email + `</td>
                  <td><button type="button" class="delete-row">Delete Row</button></td>
              </tr>
            `;

        //VALIDATION
        if (name && email) {
            $("table tbody").append(markup);
            $('.req').remove();
        } else {
            $('.req').remove();
        }

        //REQUIRED
        if (!name) {
            $('#name').after(`
                <div class="req">
                    <small class="text-secondary text-danger" style="font-size: 10px;"> 
                        <i>* Name must not be empty</i>
                    </small>
                </div>
              `);
        }

        if (!email) {
            $('#email').after(`
                <div class="req">
                    <small class="text-secondary text-danger" style="font-size: 10px;"> 
                    <i>* Email address must not be empty</i>
                    </small>
                </div>
              `);
        }
    });

    $(".delete-row").click(function() {
        $(this).parents("tr").remove();
    });

});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7c5c8c8d3d4d3d5c6d7e79389918997">[email protected]</a>/dist/css/bootstrap.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<div class="container mt-2">
    <form>
      <div class="row">
        <div class="col-4">
            <input type="text" id="name" placeholder="Name" class="form-control" required>
        </div>
        <div class="col-4">
            <input type="text" id="email" placeholder="Email Address"  class="form-control" required>
        </div>
        <div class="col-4">
          <button type="button" class="add-row btn btn-success"> ADD </button>
        </div>
      </div>
    </form>
    <br>
    <br>
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Select</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
          <tr>
            <td>One 1</td>
            <td>One 1</td>
            <td><button type="button" class="delete-row">Delete Row</button></td>
          </tr>
          <tr>
            <td>Two 2</td>
            <td>Two 2</td>
            <td><button type="button" class="delete-row">Delete Row</button></td>
          </tr>
          <tr>
        </tbody>
    </table>
   </div>

Answer №1

Try replacing your event with

$(document).on('click', '.delete-row', function(){})
. This will create an event for all '.add-row' elements on the page, including any new ones that are added dynamically.

If you stick with using

$('.delete-row').click(function(){})
, it will only create an event for the existing rows and not for any dynamic ones.

Take a look at this fiddle: https://jsfiddle.net/Alex197/y40kq2x6/1/

$(document).ready(function(){
  $(document).on('click', ".add-row", function(){
    var name    = $("#name").val();
    var email   = $("#email").val();
    var markup  = `
      <tr>
      <td>`+name+`</td>
      <td>`+email+`</td>
      <td>
      <button type="button" class="delete-row">Delete Row</button>
      </td>
      </tr>
      `;

    //VALIDATION
    if(name && email){
      $("table tbody").append(markup);
      $('.req').remove();
    }else{
      $('.req').remove();
    }

    //REQUIRED
    if(!name){
      $('#name').after(`
        <div class="req">
        <small class="text-secondary text-danger" style="font-size: 10px;"> 
        <i>* Nama Tidak Boleh Kosong</i>
        </small>
        </div>
        `);
    }

    if(!email){
      $('#email').after(`
        <div class="req">
        <small class="text-secondary text-danger" style="font-size: 10px;"> 
        <i>* Nama Tidak Boleh Kosong</i>
        </small>
        </div>
        `);
    }
  });
        
  $(document).on('click', ".delete-row", function(){
    $(this).parents("tr").remove();
  });
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74161b1b00070006150434405a425a44">[email protected]</a>/dist/css/bootstrap.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<div class="container mt-2">
    <form>
      <div class="row">
        <div class="col-4">
            <input type="text" id="name" placeholder="Name" class="form-control" required>
        </div>
        <div class="col-4">
            <input type="text" id="email" placeholder="Email Address"  class="form-control" required>
        </div>
        <div class="col-4">
          <button type="button" class="add-row btn btn-success"> ADD </button>
        </div>
      </div>
    </form>
    <br>
    <br>
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Select</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
          <tr>
            <td>One 1</td>
            <td>One 1</td>
            <td><button type="button" class="delete-row">Delete Row</button></td>
          </tr>
          <tr>
            <td>Two 2</td>
            <td>Two 2</td>
            <td><button type="button" class="delete-row">Delete Row</button></td>
          </tr>
          <tr>
        </tbody>
    </table>
 </div>

Answer №2

@alex197 suggested replacing

$(document).on('click', '.add-row', function(){})
. Here is the updated working code:

$(document).ready(function(){

           $(".add-row").click(function(){
            var name    = $("#name").val();
            var email   = $("#email").val();
            var markup  = `
              <tr>
                <td>`+name+`</td>
                <td>`+email+`</td>
                <td>
                  <button type="button" class="delete-row">Delete Row</button>
                  </td>
                </tr>
            `;
          
            //VALIDATION
            if(name && email){
                $("table tbody").append(markup);
                $('.req').remove();
            }else{
                $('.req').remove();
            }
            
            //REQUIRED
            if(!name){
                $('#name').after(`
                <div class="req">
                  <small class="text-secondary text-danger" style="font-size: 10px;"> 
                    <i>* Name cannot be empty</i>
                    </small>
                  </div>
              `);
            }
            
            if(!email){
                $('#email').after(`
                <div class="req">
                  <small class="text-secondary text-danger" style="font-size: 10px;"> 
                    <i>* Email cannot be empty</i>
                    </small>
                  </div>
              `);
            }
        });
        

          $(document).on('click', '.delete-row', function(){
                $(this).parents("tr").remove();
        });
        
 });
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35575a5a41464147544575011b031b05">[email protected]</a>/dist/css/bootstrap.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<div class="container mt-2">
    <form>
      <div class="row">
        <div class="col-4">
            <input type="text" id="name" placeholder="Name" class="form-control" required>
        </div>
        <div class="col-4">
            <input type="text" id="email" placeholder="Email Address"  class="form-control" required>
        </div>
        <div class="col-4">
          <button type="button" class="add-row btn btn-success"> ADD </button>
        </div>
      </div>
    </form>
    <br>
    <br>
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Select</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
          <tr>
            <td>One 1</td>
            <td>One 1</td>
            <td><button type="button" class="delete-row">Delete Row</button></td>
          </tr>
          <tr>
            <td>Two 2</td>
            <td>Two 2</td>
            <td><button type="button" class="delete-row">Delete Row</button></td>
          </tr>
          <tr>
        </tbody>
    </table>
   </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The HTML output generated by JSF component libraries is subpar. Is this level of quality really acceptable?

Back when I worked on web-apps using jsp/jstl and jQuery, I made sure to keep my HTML clean and separate from styles and scripts. JSP would sometimes add unnecessary spaces and blank lines, but that was pretty much it. Now I'm giving jsf a try for de ...

The function mysql_fetch_assoc is displaying absolutely nothing (neither null, nor 0, nor an empty string)

I'm encountering an issue with retrieving data from my $result variable. Everything works smoothly when there is one result, but if I try to check for a result and find none, the $array ends up empty. Running both commands below results in nothing bei ...

Problem with memory management in ThreeJS

After developing a ThreeJS app using the canvas renderer to meet project requirements, I encountered a memory and garbage collection issue. As part of the application logic, numerous meshes are created for animations on sections of a flat 2D donut or ring ...

What is preventing Node.js from executing my JavaScript code in the terminal?

https://i.sstatic.net/JJmg2.jpg I need help understanding why my JavaScript code isn't working properly. Can someone explain the Uncaught SyntaxError: Unexpected Identifier error message? ...

The onblur function is not being triggered

Recently, I encountered an issue while trying to invoke a JavaScript function onblur of a field. The main problems I faced were: 1) The popup inside the function call was triggered automatically during page load. 2) When attempting to access the functio ...

Utilizing Angular.js to nest directives seamlessly without cluttering the markup

Expressing my query might pose some difficulty, but I appreciate your patience. I comprehend that in the realm of Angular.js, directives play a crucial role in driving dynamic markup. What was once achieved through jQuery can now be accomplished using dir ...

Retrieve pairs of items from a given variable

Containing values in my 'getDuplicates' variable look like this: getDuplicates = 100,120,450,490,600,650, ... These represent pairs and ranges: Abegin,Aend,Bbegin,Bend My task is to loop through them in order to apply these ranges. var ge ...

Creating a flexible grid layout using Flexbox and JavaScript media queries to dynamically adjust container size

I enjoy working on Etch-a-Sketch projects from The Odin Project, but I am looking to take it a step further than just the assignment. I want to challenge myself by achieving this solely with Flexbox and JavaScript, without involving CSS Grid. When I se ...

Custom dropdown feature in Vue-tables2

Is there a way to customize the select dropdown style in vue-tables2 table? I am trying to change the entire template of the dropdown, not just add CSS classes. My custom template includes additional elements like span and div tags that need to be incorpor ...

Guide on incorporating factories with Ionic/Angular JS while utilizing phonegap

I've been experimenting with global variables in my ionic/angular + phonegap app project by implementing a factory service. However, even adding a simple factory service like the one below somehow disrupts the app and causes all screens to turn compl ...

The total value of elements that are constantly changing

Is there a way to calculate the real-time sum of dynamic elements' values, but I seem to be struggling with it. Check out my DEMO here. Here is the code snippet I am using: My Javascript code: <script> $(document).ready(function(){ ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

Creating an .htaccess configuration for managing case-sensitive file names

Today marked the official launch of my new website, but I've encountered some unexpected issues with the .htaccess file. Despite my best efforts to address them prior to going live, it appears that there are still unresolved problems. You can visit t ...

Guide on removing a row from a mySql table with the help of AJAX

let tableName = "users"; let userID = 25; $("#btndel").click(function() { if (confirm("Are you sure you want to delete this item?")) { $.ajax({ url: 'ajaxdel.php', type: 'post', data: { ...

Having trouble viewing objects' content in the JavaScript console in Visual Studio 2015?

In the past, I was able to see all the content of my JavaScript objects like this: However, for some reason now, the content is not being displayed at all: I am using Visual Studio 2015 Community with Cordova and Ripple emulator. I have tried creating a ...

Steps to fully eliminate the recent action panel from Django's administrative user interface

Is there a way to completely remove the recent action panel from Django admin UI? I have searched extensively but all the information I find is about clearing the data in the panel from the database. What I'm looking for is a way to entirely eliminate ...

Tips on implementing SCSS styles in my create-react-app application along with Material UI components?

I recently developed a React app using Create-React-App, and now I am looking to incorporate Material UI with styling through SCSS. https://i.sstatic.net/JLEjX.png To manage my styles, I created a main.css file using node-sass. While attempting to apply ...

What are the outcomes when invoking jQuery.post() with a blank URL parameter?

Is it true that when I submit a form with an empty action field, it will automatically submit to the current page? How does this behavior change when using ajax requests? ...

What is the best way to toggle dropdown menu items using jQuery?

Upon clicking on an li, the dropdown menu associated with it slides down. If another adjacent li is clicked, its drop down menu will slide down while the previous one slides back up. However, if I click on the same li to open and close it, the drop down m ...

Sharing data between view and controller in Laravel: a guide

Currently, I am developing a product cart feature that includes subtotal and grand total values displayed within <span> tags. My goal is to pass the grand total value to the controller for further processing. However, I encountered an issue where the ...