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

The cloned rows created with jQuery are failing to submit via the post method

Hello, I am currently working on a project in Django and could use some assistance with my JavaScript code. Specifically, I am trying to incorporate a button that adds new rows of inputs. The button does function properly as it clones the previous row usin ...

Transforming Several Dropdowns using jQuery, JSON, and PHP

Hey there! I'm looking to update the state depending on the country and city based on the chosen state. <label>Country:</label><br/> <select onchange="getval(this)"> <option value="">Select Country</op ...

Guide to implementing a seamless Vue collapse animation with the v-if directive

Struggling with Vue transitions, I am attempting to smoothly show/hide content using v-if. Although I grasp the CSS classes and transitions involved, making the content appear 'smoothly' using techniques like opacity or translation, once the anim ...

During the serialization process of a System.Reflection object, a circular reference was identified

One of my asp.net MVC 3 controller action methods looks like this: public JsonResult GetRecordingRates(int Id) { List<DefaultRateChart> defaultRateCharts = new List<DefaultRateChart>(); using (IDefaultRateChartManager defau ...

Perhaps dividing numbers with regular expressions

My HTML textarea allows users to input numeric serial numbers in various formats - either inline, separated by any character, or in columns from an Excel file. The serial codes are either 14 characters long if the first character is "1," or always 15 char ...

Vertical text alignment alongside an image in multiple lines

I have been struggling with aligning multi-line text next to an image in a responsive design. No matter what I try, when the browser window is resized and the text becomes multi-lined, it always falls below the image positioned to the left of it. Can any ...

Validate all JavaScript buttons by binding a click event

I've implemented the JS validation plugin from this source and it's functioning properly. However, it captures all button clicks on the page, including when I click on Back to Home, triggering form validation unnecessarily. I only want the form ...

Ways to guarantee that only one accordion tab is open at a time while keeping it open continuously

Hey everyone, I'm just starting to learn how to code and still getting the hang of using Stack Overflow so please bear with me if my question isn't perfectly formatted. I have created an accordion that is almost functioning correctly, but I need ...

CSS Opacity Issue

Why is the article transparent? Despite my efforts to search online for similar instances, I am surprised at not finding anything and feeling quite puzzled about what steps to take next. body { background-color: #000000; opacity: 0.8; background-i ...

My images seem to lose control and go completely wild when I try to turn them into hyperlinks

Seeking advice on why my social icons are behaving strangely. This is a new issue for me and I suspect that some other CSS is causing the problem, but I can't seem to locate it. I want to ensure that the formatting of these images remains consistent ...

Create a dynamic onClick event script and integrate it into Google Optimize

I need to incorporate a button element into my website using Google Optimize for an experiment. This button needs to trigger a specific script depending on the variation of the experiment. I have attempted two different methods: <button id="my-button" ...

Why isn't the class applying the color to the Angular span element?

My Angular application generates text that needs to be dynamically colorized. To achieve this, I inject a span element with a specific class into the text output like so: Some text <span class="failResult">that's emphasized</span> and oth ...

Extracting information from Python Bottle with the help of AJAX jQuery

I'm currently working on an HTML page that communicates with a Python script returning a JSON string through AJAX/jQuery. I've set up Bottle for basic URL routing functionality. The issue I'm facing is that my browser indicates that the AJA ...

Customize tab background color in Material-UI by utilizing a styledTab component with a passed prop

I've customized this tab to have my desired style: import { withStyles } from "@material-ui/core/styles"; const StyledTab = withStyles((theme) => ({ root: { backgroundColor: "yellow", }, }))((props) => { const { shouldSetBackgroundCol ...

Embed the YouTube video using the URL in the video tag

I tried using the <video> tag, but I'm having trouble getting it to play videos from YouTube. Even though I found this http://jsfiddle.net/wCrNw/, it doesn't seem to work as expected. I also consulted Show Youtube video source into HTML5 ...

Transitioning images smoothly and responsively with jQuery, creating a beautiful

Hey there! I'm looking for some help with transforming this jQuery effect. Instead of having fixed sized images, I want to set the size in percentage (width:100%; height:auto) so they can be responsive. Any creative ideas or suggestions? <scri ...

Arranging two list items (<li>) side by side in HTML code

I am currently designing a form with a side navigation bar that will display around 15-20 elements. Each element is represented by an <li> containing a link to open a modal when clicked. This is the current structure of my code: <div id="sidebar ...

"Unsuccessful jSON request made by Ajax resulting in undefined response

I've implemented an ajax call to fetch data from a json file and display it in an HTML table. Everything was working fine initially, but now it seems to be returning UNDEFINED. Could it be that the data from the json file hasn't finished loading ...

Tips for getting rid of the excess space surrounding an image within a div tag

Placing images inside bootstrap card divs within col divs is my current challenge <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" /> <div class="container"> <div class="row"& ...

Reduce the density of x-axis labels in highcharts

Do you have any input on Highcharts? This chart belongs to me: I am looking to reduce the density of x-axis labels, similar to the y-axis. Your assistance is greatly appreciated. Edit: for instance, take a look at this example: http:// jsfiddle.net /vu ...