Overcomplicating div elements with unnecessary cloning during checkbox usage

Whenever I check the checkbox and press OK, I want to clone a div with specific user details. Everything works as expected when selecting multiple users. However, adding more users without unchecking the previous checkboxes results in cloned buttons but not the divs. If I remove $div.remove();, the div is cloned correctly on the right side, but the values are incorrect. The last div should be removed, but that's where I encounter issues.

$(document).ready(function(){
    $('#delivery-assignment-ok').click(function(){
      var totalamount = 0;
      countCheck = $("input[name='check']:checked").length;
    $.each($("input[name='check']:checked"), function(){            
                // alert(this.id);
                
          var data=this.id;
          // alert(data);
          var id=data.split(" ");
          // alert(id[0]);
          var $div = $('div[id^="deliverydata"]:last');
          
            var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
            
              // alert(num);
          if (this.value == "False") {

              this.value = "True";
            var $clone = $div.clone().prop('id', 'deliverydata'+num );
            $clone.find('#delivery_orderId').prop('name','delivery_orderId'+num);
            $clone.find('#delivery_orderId').val("").end();
            $clone.find('#delivery_order_city').prop('name','delivery_order_city'+num);
            $clone.find('#delivery_order_city').val("").end();
            $clone.find('#delivery_order_address').prop('name','delivery_order_address'+num);
            $clone.find('#delivery_order_address').val("").end();
            $div.find("#delivery_orderId").val(id[0]);
            $div.find("#delivery_order_city").val(id[1]);
            $div.find("#delivery_order_address").val(id[2]);
            $div.after($clone).append('<button class="btn btn-primary">Delete</button>');
         
            $div.children().next().css({
              'float':'right',
                  'position': 'relative',
                  'top': '30px'
              }) ;
               $div.children('.row.form-group').css({
              'width':'91%',
              'float':'left'
            });
          
        }
         
        });
      if (countCheck != 0) {
        var $div = $('div[id^="deliverydata"]:last');
        $div.remove();

      }

    });
  });
...

codesnippet is attached below

Answer №1

To simplify the process, avoid using IDs in duplicated records. Dynamic IDs can be difficult to use as identifiers. Instead of IDs, use name arrays by adding [] to the name. This will send the data as an array in the form.

I implemented event delegation for the delete buttons to work with all records. Alternatively, you could assign the function to a dummy object and use clone(true) if preferred.

A hidden dummy row is created that will be cloned and filled based on selected rows. A data attribute is utilized to match them against table rows to prevent data deletion when adding new rows.

This approach significantly reduces the amount of code required.

$(document).ready(function() {
  //Make delete buttons work with event delegation
  $('#products').on('click', '.btn-delete', function() {
    $(this).parents('.deliverydata').remove();
  });

  //When assigning tasks
  $('#delivery-assignment-ok').click(function() {
    //Loop over the tr elements
    $.each($("#myTable tr"), function() {
      $tableRow = $(this);
      $checkbox = $tableRow.find('.rowSelect');
      
      var checkboxId = $checkbox.attr('id');
      
      //If row is checked and not added yet then add it
      if ($checkbox.is(':checked')) {
        if ($('#products div[data-checkboxid="' + checkboxId + '"]').length === 0) {
          var $clone = $('#productrow_dummy .deliverydata').clone();
          //Set corresponding row checkbox id as a data attribute
          //For some reason jQuery.fn.data() doesn't seem to work on cloned objects, attr() works fine.)
          $clone.attr('data-checkboxid', checkboxId);
          //Set input values
          $clone.find('.delivery_orderId').val($tableRow.find('.orderId').text());
          $clone.find('.delivery_order_city').val($tableRow.find('.deliveryOrdeCity').text());
          $clone.find('.delivery_order_address').val($tableRow.find('.deliveryOrderAddress').text());
          //Append clone
          $clone.appendTo('#products');
        }
      }
      //Else remove when a corresponding element is found.
      else {
        $('#products div[data-checkboxid="' + checkboxId + '"]').remove();
      }
    });
  });
});
#productrow_dummy {
  display: none;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>



<div class=" list-group items">

  <table class="table table-striped table-search" id="myTable">
    <thead>
      <th><input type="checkbox" name="check"></th>
      <th>Order ID</th>
      <th>City</th>
      <th>Receiver Address</th>
      <th>Amount</th>
    </thead>
    <tbody>
      <tr>
        <td><input type="checkbox" class="rowSelect" name="check" data-filter-item data-filter-name="1234 Kathmandu Koteshwor 3000" id="1234 Kathmandu Koteshwor 3000"></td>
        <td class="orderId">1234</td>
        <td class="deliveryOrdeCity">Kathmandu</td>
        <td class="deliveryOrderAddress">Koteshwor</td>
        <td>Rs. 3000</td>
      </tr>
      <tr>
        <td><input type="checkbox" class="rowSelect" name="check" data-filter-item data-filter-name="123 Kathmandu Koteshwor 3000" id="123 Kathmandu Koteshwor 3000"></td>
        <td class="orderId">123</td>
        <td class="deliveryOrdeCity">Kathmandu</td>
        <td class="deliveryOrderAddress">Koteshwor</td>
        <td>Rs. 3000</td>
      </tr>
      <tr>
        <td><input type="checkbox" class="rowSelect" name="check" data-filter-item data-filter-name="12 Kathmandu Koteshwor 3000" id="12 Kathmandu Koteshwor 3000"></td>
        <td class="orderId">12</td>
        <td class="deliveryOrdeCity">Kathmandu</td>
        <td class="deliveryOrderAddress">Koteshwor</td>
        <td>Rs. 3000</td>
      </tr>
      <tr>
        <td><input type="checkbox" class="rowSelect" name="check" data-filter-item data-filter-name="14 Kathmandu Koteshwor 3000" id="14 Kathmandu Koteshwor 3000"></td>
        <td class="orderId">14</td>
        <td class="deliveryOrdeCity">Kathmandu</td>
        <td class="deliveryOrderAddress">Koteshwor</td>
        <td>Rs. 3000</td>
      </tr>
      <tr>
        <td><input type="checkbox" class="rowSelect" name="check" data-filter-item data-filter-name="123456 Kathmandu Koteshwor 3000" id="123456 Kathmandu Koteshwor 3000"></td>
        <td class="orderId">123456</td>
        <td class="deliveryOrdeCity">Kathmandu</td>
        <td class="deliveryOrderAddress">Koteshwor</td>
        <td>Rs. 3000</td>
      </tr>
      <tr>
        <td><input type="checkbox" class="rowSelect" name="check" data-filter-item data-filter-name="1234567 Kathmandu Koteshwor 3000" id="1234567 Kathmandu Koteshwor 3000"></td>
        <td class="orderId">1234567</td>
        <td class="deliveryOrdeCity">Kathmandu</td>
        <td class="deliveryOrderAddress">Koteshwor</td>
        <td>Rs. 3000</td>
      </tr>
    </tbody>
  </table>
</div>
<input type="button" id="delivery-assignment-ok" name="delivery-assignment-ok" class="btn-primary ok" value="Assign Task">

<div class="row">
  <div class="col-md-12">
    <div class="heading">
      <h3>Other Details</h3>
    </div>
    <div id="products">

    </div>
    <div id="productrow_dummy">
      <div class="deliverydata">
        <div class="row form-group">
          <div class="col col-md-4">
            <label>Order ID</label>
            <input type="text" name="delivery_orderId[]" class="form-cont## Heading ##rol delivery_orderId">
          </div>
          <div class="col col-md-4">
            <label>City</label>
            <input type="text" name="delivery_order_location[]" class="form-control delivery_order_city">
          </div>
          <div class="col col-md-4">
            <label>Receiver Address</label>
            <input type="text" name="delivery_order_location[]" class="form-control delivery_order_address">
          </div>
          <button class="btn btn-delete">Delete</button>
        </div>
      </div>
    </div>
  </div>

Answer №2

This piece of code is in desperate need of some cleaning up. The current design is poor as removing the last item in #products can cause issues for the next item that relies on it. However, simply hiding the last item seems to provide the functionality required. Consider replacing

if (countCheck != 0) {
    var $div = $('div[id^="deliverydata"]:last');
    $div.remove();
}

with

if (countCheck != 0) {
    $('div[id^="deliverydata"]').show();
    $('div[id^="deliverydata"]:last').hide();
}

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

Position icons and images on the right side, and the textarea on the left side of the page (using Twitter

Summary: Here is the desired end result shown in the image below. Alternatively, you can refer to the JSFiddle. Ideally, only CSS should be used without changing the DOM structure. The icons need to be aligned completely to the right using the .pull-right ...

What are the steps to employ a query string to display a specific image?

If I understand correctly, I can utilize a query string and parse it to display certain information. How would I apply that concept to load a specific image? https://codepen.io/anon/pen/qYXexG <div id="gallery"> <div id="panel"> <img ...

Instead of accessing the HTML page directly, you can view the source page by using the F12

I need to extract both data and IPs from VirusTotal.com using selenium and Beautiful Soup in Python. When I make a get request, I only receive the view-source HTML instead of the complete data-rich HTML shown in Inspect mode (F12). Does anyone have any su ...

As the number of lines increases by x%, CSS gradients gradually fade away during the generation process

Is there a way to create a gradient that displays a red line every x% without the colors fading into white? As I add more lines, the red stripes seem to lose their intensity and blend into a white background. The .four-stripes selector creates a good resu ...

Adjust the dimensions of a nested element within a container that has padding applied

After browsing through numerous similar questions regarding this issue, I have not been able to find a solution that works for my specific case. The HTML code in question is as follows: a{ display: block; padding: 3px 20px; clear: both; font-weight: ...

A JavaScript variable... cannot access

Can anybody explain to me the reason behind this reference not functioning properly? let linkId = $(this).attr("data-id"); //retrieve the id data when a tag is clicked $(".wrapper").find("section[id=linkId]").css({"background-color": "red"}); ...

Unable to get ajax Post to function properly

Looking to save an object on a restful server, I attempted using an HTML form which worked fine. However, when trying it with JavaScript, I encountered some issues. Here's the code snippet: var app2={"user_id" : seleVal, "name":nome2, "img":img2, "ty ...

The code functions perfectly on my local machine, however it is not cooperating on the HostGator server

A selection box based on values should appear in text fields, The current code is functional in local host but not working on the hostgator server For example, displaying country options based on the selected state and districts based on the selected sta ...

Incorporating Scatter Dots into a Horizontal Stacked Bar Chart using Chart.js

My horizontal stacked bar chart is not displaying pink scatter dots based on the right y axis numbers. I need help figuring out what I am doing wrong. When I change the chart to a normal bar instead of horizontal, the dots appear. However, I require them ...

Executing Ajax requests to interact with a RESTful API

After developing a back end REST API using Slim Framework and closely following the REST format, I ran into an issue when working on the Front End. It seems that AJAX functions well with parameters but not paths. I am considering outsourcing or creating a ...

As the window width decreases, the image is breaking free from its container

When the window is in full screen, such as lg or md, the content fits within the container. However, when I resize the window to be smaller, the image overflows outside of the container. This layout was created using Bootstrap 3. Below is the HTML and CSS ...

How can I center a text element vertically within its parent div element?

After researching various solutions to align text within a div, I have found that many recommend using the vertical-align property. Despite trying this method, it does not seem to work for my specific case. .free { display: inline-block; -webkit-bor ...

When the direction is set to rtl, special characters that are supposed to be at the

When using the direction property for a label with windows style directory paths containing backslashes, I encountered an issue. The purpose of using direction:rtl; was to display the end part (file names) of the path. However, I found that I am getting th ...

Adjusting the color of a value in justGage requires a few simple steps to

Is it possible to modify the color and design of the text in the Value parameter of justGage after creating the gauge? My goal is to change the text color to blue with an underline to give it a link-like appearance. Appreciate your assistance. ...

Angular.js does not trigger validation for input[type='date'] if only a part of the date is entered (such as just the day)

There is an input[type='date'] with no additional validation rules. The issue arises when only a portion of the date is entered (for example, just the day and month). In this case, if you enter '01/02/YYYY', it will be recognized as an ...

Having trouble with Image and Css not displaying correctly when using CodeIgniter 3 with DomPDF?

I'm currently utilizing CodeIgniter 3 and dompdf to convert an HTML view into a PDF. While I am able to successfully convert the HTML to PDF, the proper styling is not being applied. All necessary CSS files have been included as custom design in the v ...

`Problem with data representation in PDF regarding page dimensions and layout`

I am currently using the datatable plugin to enable exporting to PDF, CSV, XLS, and for printing purposes. However, I am facing an issue with the PDF view. When I attempt to download the PDF file by clicking on the button, the data in the PDF does not app ...

Navigate quickly to different sections using jump links and adjust the positioning with the style attribute, such as "padding-top

My website incorporates Jump Links to navigate between page elements as part of an interactive User Guide. Everything functions properly on Firefox, IE, and Edge, but Chrome and Opera seem to disregard the 'padding'. Due to a fixed menu bar on t ...

Creating JavaScript Powered Pie Charts

I am seeking a lightweight JavaScript pie chart option to replace PlotKit, as the library is too large for my low bandwidth. Ideally, I am looking for a compact and efficient solution in either JavaScript or jQuery. ...

Scrolling to the top of the Popper component when an element is selected

I am currently utilizing the Autocomplete Material UI control with multiple selections enabled. Here is the code snippet I have created based on this answer: <Autocomplete PopperComponent={PopperMy} ... /> const PopperMy = function (props) ...