How can I use jQuery to dynamically add and remove input values?

I am having trouble with saving and deleting values in a table row. I have an input field and an add button. When I click on the add button, I want the input value to be saved in a table row with a delete button next to it. I need to be able to delete individual values. I have tried using jQuery, and while I can add values to the table, I am unable to delete them. Here is my code. Any help would be appreciated.

https://i.sstatic.net/mqmRE.jpg

<div class="col-sm-6 col-md-5">
              <div class="form-group">
                <label class="control-label" for="supplyingLocation">Supplying to Location <span class="text-danger">*</span></label>
                <div class="input-group">
                <input type="text" class="form-control" placeholder="Enter Supplying Location Name" name="supplyingLocation" id="supplyingLocation" required="required">
                <div class="input-group-btn">
                  <button class="btn btn-primary add-supplying-location-row" type="button">Add Location </button>
                </div>
              </div>
              </div>
            </div>
            <div class="clear"></div>
            <div class="col-sm-5">
                <div class="listing-table">
                <div class="table-responsive sup-loc-table">
                <table class="table table-bordered">
                  <thead>
                      <tr>
                        <th>Supplying to Location</th>
                        <th>Action</th>
                      </tr>
                  </thead>
                  <tbody></tbody>
                </table>
                </div>

          </div>
          </div>

 <script>
    $(document).ready(function(){
        $(".add-supplying-location-row").click(function(){
            var supname = $("#supplyingLocation").val();
            $('#supplyingLocation').val('');
            var supmarkup = "<tr><td>" + supname + "</td><td><input type='button' name='supplyingLocRecord' value='Delete' id='deletesupLoc'></td></tr>";
            $(".sup-loc-table table tbody").append(supmarkup);

        });

        // Find and remove selected table rows

        $("#deletesupLoc").click(function(){
            $(".sup-loc-table table tbody").find('input[name="supplyingLocRecord"]').each(function(){
                {
                    $(this).parents("tr").remove();
                }
            });
        });
    });    
</script>

Answer №1

You were on the right track with your answer. Here are some key points to keep in mind:

  1. First: Avoid using duplicate IDs. While it may work, it is not semantically correct. Instead, use the same class when adding the same row onclick.

  2. Second: The same principle applies to the name attribute. If you need to capture multiple data of the same type, use supplyingLocRecord[]. This will capture all elements into a single array.

    <input type='button' name='supplyingLocRecord[]' value='Delete' class='deletesupLoc'>

  3. Third: The click() binding you're utilizing is a "direct" binding, which only attaches the handler to existing elements. To ensure it works for elements created in the future, use a "delegated" binding with on().

    $(document).on('click','.deletesupLoc',function(){
          $(this).parents("tr").remove();
        });

Answer №2

One reason why the button identified by deletesupLoc is not found in the DOM when .click() is called on it is because it is dynamically added by your script. As a result, jQuery is not aware of this button's existence at that moment. To address this issue, you should attach an event listener to the newly created element by using $(document).on('click') when creating the button.

I made a slight adjustment to your code so that each button has a unique ID (unless the same name is entered multiple times - you can either prevent this or add a number to the ID to make it unique). This modification enables you to delete the corresponding row in the table:

// Locate and delete selected table rows
function deleteRow(buttonId) {
    $("#" + buttonId).each(function(){
        {
            $(this).parents("tr").remove();
        }
    });
};

$(document).ready(function(){
  $(".add-supplying-location-row").click(function(){
    var supname = $("#supplyingLocation").val();
    $('#supplyingLocation').val('');
    var buttonId = "deletesupLoc" + supname.replace(" ", "");
    var supDeleteButton = $("<input type='button' name='supplyingLocRecord' value='Delete' id='" + buttonId + "'>");
    $(document).on('click', '#' + buttonId, function() { deleteRow(buttonId); });
    var supRow = $("<tr>");
    supRow.append("<td>").append(supname);
    supRow.append("<td>").append(supDeleteButton);
    $(".sup-loc-table table tbody").append(supRow);
  });
});    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="col-sm-6 col-md-5">
              <div class="form-group">
                <label class="control-label" for="supplyingLocation">Supplying to Location <span class="text-danger">*</span></label>
                <div class="input-group">
                <input type="text" class="form-control" placeholder="Enter Supplying Location Name" name="supplyingLocation" id="supplyingLocation" required="required">
                <div class="input-group-btn">
                  <button class="btn btn-primary add-supplying-location-row" type="button">Add Location </button>
                </div>
              </div>
              </div>
            </div>
            <div class="clear"></div>
            <div class="col-sm-5">
                <div class="listing-table">
                <div class="table-responsive sup-loc-table">
                <table class="table table-bordered">
                  <thead>
                      <tr>
                        <th>Supplying to Location</th>
                        <th>Action</th>
                      </tr>
                  </thead>
                  <tbody></tbody>
                </table>
                </div>

          </div>
          </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

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

What is the best way to activate a CSS animation?

I've hit a roadblock while attempting to trigger a CSS animation. Here's my CSS: h3[id="balance-desktop"]{ color: black; -webkit-animation-name: gogreen; -webkit-animation-duration: 2s; animation-name: gogreen; animation-du ...

AJAX/PHP causing delays due to lag problems

I've been trying to implement an asynchronous call in my PHP script, but I keep running into the same issue: "Maximum call stack size exceeded." This is causing severe lag on my site and I suspect there might be a loop somewhere in my code that I just ...

Disabled: AJAX Submit Button

I am looking to create a dynamic search functionality using PHP and AJAX. The goal is to select specific search results using checkboxes and insert them into another table in the database. Below is the code to query the search in a table: <?php // ...

Creating personalized tags or components by utilizing insertAdjacentHTML in Vue

With the use of insertAdjacentHTML, I am able to create HTML elements such as div and span, but it seems that I cannot generate custom tags like <myComponent> </myComponent>. I understand that insertAdjacentHTML can create HTML elements, but a ...

Trouble aligning Material UI data-table columns (table head) to center in React

I have a data table where I declare rows and columns as simple variables, making it difficult to style them using 'style={{textAlign: center}}'. I tried adding a CSS file, but it did not work with the Material UI table. I am unsure of how to proc ...

Generate a series of rotations ranging from -60 to 60 using d3.cloud

I need help replicating the word cloud feature found on for my website. After studying examples and referencing a Stack Overflow answer, I put together the following code: var fill = d3.scale.category20(); var layout = d3.layout.cloud() .size([900, ...

What is the best way to enlarge text size with jquery?

I am attempting to: $('a[data-text="size-bigger"]').click(function () { a=$('span'); b=$('span').css('font-size'); a.css('font-size', b+1); } ); Initially, I ha ...

The Detail Button is unable to transmit data when used in conjunction with ajax pagination

Hey everyone! I've got a script for ajax pagination that's working well. Let me share it with you all: function show_tour_type(v,t) { $(".cl_tour_type").html('<div align="center"><img src="<?php echo base_url(); ?>assets/ ...

Unable to update navigation link color in Bootstrap 4 styling

<nav id="section_navbar" class="navbar navbar-expand-lg fixed-top"> <div class="mx-auto my-2 order-0 order-md-1 position-relative"> <div id="top_logo" class="container-fluid"> <span>VirtualQR</ ...

How can one retrieve the 'alt' attribute text from an image tag on a webpage using the JSOUP library in an Android application?

Extracting the 'alt' text from an 'img' tag in Android after clicking a button is causing issues. The attempted code is not working as expected. Here is the snippet of the code that was used: Document doc = Jsoup.connect(url).get(); ...

Retrieving the character 'a' within an ajax function when the data is in Arabic language

I am facing an issue with my api that sends Arabic string data and needs to be displayed on an HTML web form using the jQuery $.ajax method. However, I am encountering a problem where ajax only receives a single character, 'a', in response as sho ...

What is causing this if statement to be consistently overlooked?

I am trying to change the class of an element when the document scroll position is greater than 300px. However, my code seems to be ignored every time. Can anyone help me figure out why? if ( $(document).scrollTop() > 300) { ...

Creating a Custom Rule for Checkbox Validation using jQuery

Can the jQuery Validation plugin be used to validate custom values on checkboxes, rather than just True or False? For instance: <input id="test" type="checkbox" name="test" value="something"> I am struggling to find a method that can check if &apo ...

Applying CSS onmousemove does not function properly in conjunction with Bootstrap framework

Currently, I have a code snippet that enables an absolutely positioned box to follow the movement of the mouse cursor: $(document).mousemove( function(e) { $(".wordbox").css({ top: "calc(" + e.pageY + "px - 0.8em)", left: e.pageX }) ...

What is preventing the addition of links to the navigation bar when using a sticky navigation bar?

Currently, I am in the process of developing a blog website using Django. One of the features I have successfully implemented is a sticky navigation bar. However, I am facing a challenge with adding links to the menu on the navigation bar due to existing ...

Achieving Horizontal Alignment of Tab Labels and Icons in Material-UI with Tabs API

I am currently attempting to customize the Material UI CSS in order to align both the phone icon and text on the same line and closer together. After doing some research, I stumbled upon the Tabs API which seemed promising. Upon further inspection, I disc ...

Why does the IMG keep loading every time the web page is refreshed?

I am experiencing an issue with my html page where the background images are not reloading when I refresh the page, but the logo image is. The background images are called through an external CSS file, while the logo is used with an <image> tag. Wh ...

Switching the input to LTR changes the overall direction to LTR while maintaining the RTL placeholder

The text input is currently set to be RTL, including both the placeholder and the actual input. The settings for this were done elsewhere. My question is how can I modify it so that only the input changes to LTR, while the placeholder remains RTL. For exa ...

What is the best way to ensure the div stays in sync with scrolling?

Trying to synchronize two divs while scrolling. Essentially, I have a page scroll and want to fix the second div when it reaches the top. Please refer to the gif icon attached for clarification. You can view my progress so far here. The current issue in ...