Manipulate sortable divs with jQuery to dynamically add or remove them, and update

Currently, I am working on a photo upload section that allows users to add and remove divs with the click of a button. You can see the functionality in action here -- fiddle

My main challenge now is getting the number counts to update correctly when a div is added, removed, or rearranged.

At the moment, the count increments properly when a new div is added, but it fails to update when a div is reordered or when other divs are removed.

// MOVE LEFT AND RIGHT FUNCTION
$( function() {
    $( "#pic-con" ).sortable();
    $( "#pic-con" ).disableSelection();
  });

$(document).on('click', '.pic-left', function (){
  var current = $(this).parents(':eq(1)');
  current.prev().before(current);

});
$(document).on('click', '.pic-right', function (){
  var current = $(this).parents(':eq(1)');
  current.next().after(current);
});

$(function(){
    var div = 0;

// ADD MORE FUNCTION
 $('.add_more').click(function(){
  div++;
   var numItems = $('div.photo-upload-box').length;
  $('#pic-con').append('<div class="photo-upload-box"><div class="photo-upload-img"><img src="https://cdn4.buysellads.net/uu/1/3386/1525211184-62491.png" /></div><div class="photo-upload-field"><input type="file" name="files" class="files" accept="image/png, image/jpeg, image/jpg" /><input type="hidden" name="file1" /></div><div class="photo-upload-settings"><div class="pic-left"><i class="fas fa-angle-left"></i></div><div class="pic-right"><i class="fas fa-angle-right"></i></div><div class="pic-remove remove"><i class="fas fa-times"></i></div>div '+div+' out of '+numItems+'</div><div class="photo-custom-time" style="display:none"><label>Duration time: </label> <input type="text" /></div></div>');
    });

 // REMOVE FUNCTION
 $(document).on("click", ".remove", function(e) { 
        e.preventDefault();
        $(this).parents(':eq(1)').remove();
        var numItems = $('div.photo-upload-box').length;
});
 })();

Answer №1

If you want to update the total count in all divs, ensure that your html includes a specific class

<div>div '+div+' out of <span class="numItems"></span></div>

This way, you will be able to easily update the number

When adding an item:

 $('span.numItems').text(numItems+1);

And when removing an item:

$('span.numItems').text(numItems);

Check out the updated fiddle here

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

Update the Parent CRM Page upon closing the child ASP.net page

This pertains to CRM 2016 on-premise implementation. In my CRM 2016 environment, I have a customized button in the command bar that utilizes a JavaScript web resource to invoke an external asp.net page hosted on another server. This external page facilita ...

How can I identify when a form has been edited in order to update the database with those changes only?

Currently, I have a form with over 50 fields. While I've successfully implemented functionality for inserting, selecting, and deleting records, I'm struggling with updating a record. Specifically, if a user only updates one or two fields out of t ...

Unexpected line break in screen element without explanation

I am currently developing a mobile web application. On the top of the page, I have designed a single line which includes a "Back" link on the left side and the page name on the right. However, instead of displaying the elements as intended, the back link ...

Change the position of the background image when hovering over the div element

Looking for advice on how to create a div with a background image that only appears when hovered over. I also want the image to either zoom in or move to the sides while hovering. Here is my current progress. .seg1 p:first-child { font-size: 20px; p ...

Can Puppeteer be utilized for converting PDFs to HTML format?

Is it possible to convert PDF to HTML in addition to HTML to PDF? I haven't come across any resources that address this specific conversion process. ...

When a specific JavaScript function is triggered, the value of an HTML control will reset to its original default value

I have a form with a specific requirement. I need to allow users to input data in a text field and press enter, which should dynamically create new controls like another text field, a dropdown menu, and another text field using jQuery. While the functional ...

Inputting information into the Django database simply by hitting the enter key

I am encountering an issue while attempting to insert data into the database. Despite clicking the Submit button, no data is being added. The same outcome occurs when pressing the enter key. Below is my HTML file: <script> $(document).keypress(f ...

How to create a sequence of queries to a mongoDB database (using mongoose) depending on a condition

Source Code let placeForSearch="hampi" let filteredHotelFacilities=req.body.filter //["Free Wifi"] let hotels = await Hotel.find({placeForSearch}) .where("facilities") .select(selectedProperties) .skip(pageNu ...

What could be causing the visibility issue with my navigation items in the bootstrap navigation bar?

Currently, I am experiencing a puzzling issue with the navigation bar on my live website. The navigation items seem to flicker for a brief moment and then disappear entirely. This unexpected behavior is certainly causing me some concern. I crafted the us ...

Local variables in AngularJS across multiple Angular applications

Looking for a method to retain a local variable not affected by path or angular app changes. Attempted using $window.localStorage.set and get item, rootScope, and $window.variable with no success. ...

What is the best way to manage adding and removing table rows in Laravel while also incorporating a dropdown list?

I am trying to add more rows with the same values to a table form that includes a dropdown list generated by a @foreach loop. Here is the code: <tbody> <tr> <td> <select class="form-control" name="roo ...

Which is better: CSS gradients or background images?

Years ago, I came across many CSS codes that used background-image: url(xxx.png) to mimic a gradient background filter, as only (please correct me if I'm mistaken) IE's proprietary filter could achieve a CSS gradient. In today's world - giv ...

Screen size is incompatible with flash player

I've been using this code to try and make a swf file fit my screen or any screen it's on, but I've run into an issue. When using this code, the player in both Chrome and IE stretches to fit the screen width, but the height remains the same, ...

Using Vue.js to inject plain text into a Vue component from HTML

I am currently in the process of transitioning code from ASPX to VUE.JS. In the previous system, there was a feature that allowed plain text to be injected into HTML (such as messages with text, images, links, and inputs). However, in VUE, the injected HT ...

Example using three.js showing issues with external resources failing to load on jsfiddle.net

Currently, I am endeavoring to make progress with this sample project: github.com/josdirksen/learning-threejs/blob/master/chapter-09/07-first-person-camera.html I have made attempts at replicating the code on my personal pages.github.io account and also m ...

AngularJS allows for the passing of a function value into another function

Is there a way for me to pass a value from one function to another? Here is an example of what I am trying to achieve: HTML <div> <li ng-repeat="language in languages" ng-click="myFirstFunction(firstValue) {{lang ...

Div trigger malfunctioning

I am working with an html file that includes a button trigger using jQuery. My goal is to close a specific div when the button is clicked. Although I have attempted to use the following jQuery code in the button click event, the div is not closing. Can an ...

I am experiencing significant lag when attempting to use the Vue mouseover event to manipulate the styles of two elements. Are there any alternative methods that could achieve the same

I'm fairly new when it comes to using Vue, so I might not be approaching this in the most efficient manner. My challenge involves a table of rows generated via a v-for loop, accompanied by a list of corresponding row titles also created through a v-fo ...

Uploading files and submitting form data simultaneously via a single form with the help of AJAX

I have an HTML form with 2 input fields and a file upload form, and I would like to send this data to an index.php file using AJAX. Here is what I have done so far: <form class="col-md-3" id="form" name="reg" method="post" action="index.php" enctype="m ...

Is there a way to use regular expressions in JavaScript to match tags

As I am not very experienced with regex, my goal is to extract content from the <text> tag and the <music> tag within the given string. The expected result will be two arrays as shown below: The string to match: "<text>Chủ nhật, ng ...