Rearrange the sequence of numbers using JQuery when an HTML element is deleted

I'm currently working on a simple functionality where I have 5 rows, each with its own number.

So initially, the rows are numbered from 5 to 1. If I remove a value like 3, the sequence should adjust to 4, 2, 1, indicating that I now have only 4 rows remaining. This pattern continues as values are removed.

I've come close to getting it working, but it's not quite there yet.

Check out my JSFiddle for reference.

jQuery(function($) {
  var countercontact = 0;
  var counternum = 0;
  $("#addcontact").on('click', function() {
    countercontact++;
    $("#contact_num").append('<div class="row"><div class="form-group col-xs-1 contactspan"><span class="countercontact">' + countercontact + '.</span></div><div class="form-group col-xs-3"><input type="text" class="form-control" id="pass" placeholder="No number"></div><div class="form-group col-xs-2"><select class="form-control" id="delay"><option>5</option><option>10</option><option>20</option><option>30</option><option>40</option><option>50</option><option>60</option></select></div><div class="form-group col-xs-2">\<input type="checkbox" class="form-control" id="confirm"></div><div class="form-group col-xs-2"><input type="checkbox" class="form-control" id="enable"></div><div class="form-group col-xs-2"><button type="submit" class="btn btn-primary form-control deletecontact">Delete</button></div></div>');
    if (countercontact === 1) {
      $(".deletecontact").addClass('disabled');
    } else {
      $(".deletecontact").removeClass('disabled');
    }
  });

  $("#contact_num").on("click", ".deletecontact", function() {
    if (countercontact <= 1) {
      $(".deletecontact").addClass('disabled');
    } else {
      $(".deletecontact").removeClass('disabled');
      $(this).closest('.row').remove();
      countercontact--;
      $(".contactspan").each(function(index) {
        var ordernum = $(this).text();
        console.log(ordernum);
        if (ordernum !== 1) {
          $(this).text(parseInt($(this).text()) - 1);
        }
      });
    }
  });
});
.container {
  width: 75%;
}
.row {
  margin-bottom: 12px;
  font-size: 13px;
}
.panel {
  border: none;
  box-shadow: none;
}
.panel-heading {
  background-color: #D9DBDE;
  padding: 20px;
  margin-bottom: 10px;
  border-radius: 0;
}
.panel-heading.head {
  padding: 20px 0;
  background-color: #E1F2F9;
}
.panel-body {
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="panel panel-default">
  <div class="panel-body row">
    <div class="form-group" id="contact_num">
      <div class="row">
        <div class="form-group col-md-1">
          <label for="pass"></label>
        </div>
        <div class="form-group col-md-3">
          <label for="pass">Contact No(s)</label>
        </div>
        <div class="form-group col-md-2">
          <label for="delay">Delay</label>
        </div>
        <div class="form-group col-md-2">
          <label for="confirm">Confirm</label>
        </div>
        <div class="form-group col-md-2">
          <label for="enable">Enable</label>
        </div>
        <div class="form-group col-md-2">
          <label for="delete"></label>
        </div>
      </div>
    </div>
    <button type="submit" class="btn btn-primary" id="addcontact" style="margin-bottom: 10px;">Add</button>
  </div>
</div>

Answer №1

If you find yourself in a situation where you need to adjust numbers, you can create a function to handle that and execute it whenever necessary, such as after removing an item.

function correctIndex(){
    $('#contact_num .row').each(function(){
        $(this).find('.contactspan').html($(this).index()+1);
    });
}

Alternatively, you can modify this section of your code:

$(".contactspan").each(function(index) {
    var ordernum = $(this).text();
    console.log(ordernum);
    if (ordernum !== 1) {
    $(this).text(parseInt($(this).text()) - 1);
    }
});

to:

$(".contactspan").each(function(){
    $(this).html($(this).closest('.row').index() + '.');
});

You can view the updated fiddle here

Answer №2

Please review the code snippet below. I have updated the order number assignment as shown:

  var ordernum = 1;
  $(".contactspan").each(function(index) {
    $(this).text(ordernum);
    ordernum++;
  });

Initially set the order number to 1 and increment it for each subsequent row.

jQuery(function($) {
  var countercontact = 0;
  var counternum = 0;
  $("#addcontact").on('click', function() {
    countercontact++;
    $("#contact_num").append('<div class="row"><div class="form-group col-xs-1 contactspan"><span class="countercontact">' + countercontact + '.</span></div><div class="form-group col-xs-3"><input type="text" class="form-control" id="pass" placeholder="No number"></div><div class="form-group col-xs-2"><select class="form-control" id="delay"><option>5</option><option>10</option><option>20</option><option>30</option><option>40</option><option>50</option><option>60</option></select></div><div class="form-group col-xs-2">\<input type="checkbox" class="form-control" id="confirm"></div><div class="form-group col-xs-2"><input type="checkbox" class="form-control" id="enable"></div><div class="form-group col-xs-2"><button type="submit" class="btn btn-primary form-control deletecontact">Delete</button></div></div>');
    if (countercontact === 1) {
      $(".deletecontact").addClass('disabled');
    } else {
      $(".deletecontact").removeClass('disabled');
    }
  });

  $("#contact_num").on("click", ".deletecontact", function() {
    if (countercontact <= 1) {
      $(".deletecontact").addClass('disabled');
    } else {
      $(".deletecontact").removeClass('disabled');
      $(this).closest('.row').remove();
      countercontact--;
      var ordernum = 1;
      $(".contactspan").each(function(index) {
        $(this).text(ordernum);
        ordernum++;
      });
    }
  });
});
.container {
  width: 75%;
}
.row {
  margin-bottom: 12px;
  font-size: 13px;
}
.panel {
  border: none;
  box-shadow: none;
}
.panel-heading {
  background-color: #D9DBDE;
  padding: 20px;
  margin-bottom: 10px;
  border-radius: 0;
}
.panel-heading.head {
  padding: 20px 0;
  background-color: #E1F2F9;
}
.panel-body {
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="panel panel-default">
  <div class="panel-body row">
    <div class="form-group" id="contact_num">
      <div class="row">
        <div class="form-group col-md-1">
          <label for="pass"></label>
        </div>
        <div class="form-group col-md-3">
          <label for="pass">Contact No(s)</label>
        </div>
        <div class="form-group col-md-2">
          <label for="delay">Delay</label>
        </div>
        <div class="form-group col-md-2">
          <label for="confirm">Confirm</label>
        </div>
        <div class="form-group col-md-2">
          <label for="enable">Enable</label>
        </div>
        <div class="form-group col-md-2">
          <label for="delete"></label>
        </div>
      </div>
    </div>
    <button type="submit" class="btn btn-primary" id="addcontact" style="margin-bottom: 10px;">Add</button>
  </div>
</div>

Answer №3

The issue at hand is being triggered by the following code:

var ordernum = $(this).text();
console.log(ordernum);
if (ordernum !== 1) {
  $(this).text(parseInt($(this).text()) - 1);
}

In this scenario, ordernum is set as 1., so it needs to be converted to an integer just like within the if statement.

var ordernum = parseInt($(this).text());
console.log(ordernum);
if (ordernum !== 1) {
  $(this).text(ordernum - 1);
}

For more details, refer to https://jsfiddle.net/YvCil/ajgm9rhw/1/

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

Nodejs functions properly on a local machine, however, it encounters issues when deployed on a VPS

My nodejs/javascript code seems to be running fine on my local pc, but when I try to run it on my vps, it's not working properly. Even though I have the same node_modules installed and the code is identical. Here's a snippet of my code for refere ...

I'm looking for a way to have an element shift in a particular direction only when two keys are pressed simultaneously

Having trouble moving a square diagonally when two keys are pressed simultaneously. Trying to create an if statement that detects both key presses at the same time and triggers the movement. However, all attempts have failed so far, leaving uncertainty abo ...

Problem with Safari: File downloaded with name "Unknown" due to Javascript issue

After successfully converting my data to text/csv, I can easily download the file in Chrome. However, when attempting to do so in Safari on an iPad or Mac, it opens a tab with the name "unknown" or "Untitled". The code snippet I am using for this is as fol ...

Running a Python script through a Javascript event

I'm looking to enhance my webpage by implementing a feature where users can generate a personalized QR code with the click of a button. My current setup involves a Python script that creates the QR code image and saves it as a .png file. I want to int ...

Is there a way to remove backdrop-filter: blur effect from elements within a div?

Having an issue with a CSS property. I have designed a modal that includes inputs and labels, and I want to blur the background content. However, the problem I am facing is that the blur effect is also being applied to all elements inside the container, in ...

Is your Vue.js chart malfunctioning?

I have been experimenting with chart.js and vue.js. The component I created is called MessageGraph, and it is structured like this (with data extracted from the documentation): <template> <canvas id="myChart" width="400" height="400">< ...

What is the best way to display DT elements next to each other?

Here is a link to the code snippet: http://jsfiddle.net/ZcdkT/1/ The code renders as: DT-nameA DD-definitionA 1 DT-nameB DD-definitionB 1 DD-definitionB 2 I would like it to be formatted like this: DT-nameA DT-nameB DD-definitionA 1 ...

Unable to show inline within web forms application utilizing bootstrap

I am currently modifying the account registration section of a new VS 2013 web application that uses bootstrap css for formatting. I am working on creating a form on a page and struggling to get one section to display inline instead of as a block element. ...

Prevent certain dates from being selected in a designated input field

I am facing an issue with disabling certain array dates for a specific input field in a datepicker calendar. Even though I have included the script to exclude those dates, they are not getting disabled for that particular input field. html <input cla ...

Tips for distinguishing between 1 and 1.00 as equal, and 1.01 as not equal in Angular

How should the number 1 be treated when the decimals are zero, for example 1.000? In this case, an alert popup should appear indicating that the numbers are the same. The maximum length of the textbox should be 7 characters. For instance, 1 and 1.00000001 ...

Is it possible to create two custom WP queries that both use the same 'rand' parameter with the 'orderby' set to 'rand'?

My homepage currently displays 9 posts with a "Load More" button that fetches another 9 posts using ajax. The posts are ordered by date, but I want to change the order to random. However, when I use orderby rand in two wp_query instances, the second query ...

Modifying the action of a form using jQuery

I've been searching for solutions to my issue, but so far I haven't been able to make it work... I'm attempting to create a form action based on a menu selection. It seems like there's an error somewhere and I could use some help! $(" ...

Transforming Poloniex API Callback JSON into a compatible format for Highcharts.Stockchart

I am currently working on a project that involves retrieving JSON data from Poloniex's public API method (specifically the returnChartData method) to generate a graph using Highchart Stockchart. The graph would display the historical performance of va ...

Personalized labels for your JQuery Mobile sliders

Struggling to make this work correctly, I aim to introduce tick marks and custom labels into jQuery Mobile's slider widget. My goal is to add tick markers at 0, 25, 50, 75, and 100 with a unique string above each tick. Additionally, I want these label ...

Having trouble retrieving JSON data following file read operation

I've been on a quest to find a way to read JSON files using JavaScript. The tutorial that came the closest to what I needed is located here: https://gist.github.com/zuch/6224600. cells.json: { "cells": [ { "img": "img/singlestitch_thumb. ...

Activate ajax search in select2 by hand

I recently integrated the select2 plugin with jQuery into my website. For the most part, it functions perfectly. One particular feature I have is a search widget that utilizes select2 and remote data search. When I enter a search query using a keyboard ...

There seems to be a malfunction in the functionality of my Django template navbar

Within my project, I am utilizing two templates named base.html and contact.html. The contact.html template extends the base.html template, and these are the only two templates in use. When I navigate to the blog or about section by clicking on them, the p ...

`Optimizing Django by using multiple room relationships to save formset related models`

I need help with saving a formset that involves two models in a many-to-many relationship. When I open the page, two forms are displayed but after filling them out and clicking "Add", the fields for "phone" and "client_name" get cleared and the form is not ...

uncovering the precise text match with the help of Beautifulsoup

I am looking to retrieve the precise matching value of text from HTML using Beautiful Soup. However, I am encountering some similar text along with my desired exact match. Here is my code: from bs4 import BeautifulSoup import urllib2enter code here url="h ...

JavaScript's data.map function cannot be found

I've been developing a full stack application using Vue.Js, NodeJS, ExpressJS, and MongoDB. In my frontend code, I have a PostService.js class that manages HTTP requests to the API. However, I encountered an issue while trying to map the response data ...