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

Easy ways to manipulate the style of array components in Vue.js

Hey there all you programmers, I'm reaching out to see if any of you have insight on how I can modify the style of a specific component within an Object array. This is the code snippet: <template> <div> <ul> <li v-fo ...

Changing the structure of divs by using elements from different divs

I'm looking for some help with adjusting the CSS of a div when hovering over certain elements. Here is my current code: <div class = "container-main"> <div class = "container-inner"> <ul class = "list"> &l ...

the click event fails to trigger when the id or class is modified

Hey there, I'm new to working with jquery and I've encountered a problem. Here's the code snippet: http://jsfiddle.net/8guzD/ $('#test.off').click(function(){ $(this).removeClass('off').addClass('on'); }) ...

The div will not receive the JSON response

I am currently working with a <script> that includes functions for autocompletion and item selection: // autocomplet : this function will be executed every time we change the text function autocomplet() { var min_length = 0; // minimum character ...

Is there a way to automatically recalculate the "Total Price" when the input values are adjusted?

Whenever I add an item to the cart, it gets appended to the row in the shopping cart, and the price adjusts accordingly. However, I'm having trouble getting the price to adjust whenever I change the input values (input type: "number"). I can't se ...

What steps should I follow to successfully incorporate Zurb Foundation 4 Sections (tabs) into my Javascript Ajax functionality?

I am currently incorporating Zurb Foundation 4.1.5 into my application and I am faced with the challenge of implementing Zurb Section Javascript to handle "tabs" on the page. The content within these tabs is dynamic and fetched via Ajax calls. I am seeking ...

ReactJS component not triggering OnChange event in IE 11

While exploring the React.js documentation, I came across a suggestion to use the onChange event for text areas. Interestingly, when I tried pasting some text into an empty IE 11 text area, the onChange event failed to trigger. Surprisingly, it worked perf ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

The console is showing the Ajax Get request being logged, but for some reason it is not displaying on the

Could someone please explain why this response isn't displaying on the page? $.ajaxPrefilter( function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? &apos ...

It is essential for Jquery to properly evaluate the first JSON result, as skipping

I'm currently facing an issue where the first JSON result is being skipped when I try to evaluate a set of JSON results. Below is the Jquery code snippet in question: function check_product_cash_discount(total_id){ //check for cash discount ...

Angular JS is experiencing issues with two modules not functioning properly on a single page

Angular JS is a new technology for me. I have two modules, first2a and first22. Each module contains a controller named model1 and model2. Here is the HTML code: <!DOCTYPE html> <html > <head> <link rel="icon" ...

Tips for adjusting the default width of the container in Bootstrap3

Modifying the default width of a Bootstrap 3 container without causing any alignment issues can be a challenge. The default container width currently set is .container { width: 1170px; } However, I am looking to adjust it to .container { wid ...

Converting string patterns to regular expressions

I am utilizing mongodb to store data. My requirement is to save complete regular expressions as strings: { permissions: [{ resName: '/user[1-5]/ig', isRegex: true }] } Although I am aware of the existence of the module mongoose-rege ...

Ways to mix up a term while maintaining the original first and final characters intact (Javascript)

I've been given a task to shuffle a word that has more than 3 letters while keeping the first and last letters unchanged. The revised word should not be identical to the original, ensuring some sort of rearrangement is apparent. For example, when sh ...

Develop a library of components using TypeScript and Less files

I'm currently in the process of creating a React UI library that will consist of various components such as Buttons, Inputs, textareas, etc. This library, which I've temporarily named mylib, will be reused across multiple projects including one c ...

Using cakePHP to submit a form using ajax

While submitting a form using ajax and attempting to return a json response, I encountered an issue of receiving a missing view error. Adding autoResponder=false resulted in no response at all. This is happening while working with cakephp 2.5 In the same ...

Production environment experiences issues with Angular animations

In my MEAN stack application, I started with Sails.js. Everything was working smoothly during development, especially with angular-animate. However, once I changed the Sails environment to production, I encountered issues. Grunt is set up to concatenate a ...

Ways to retrieve text like innerText that functions across all web browsers

I need to retrieve the text from a Twitter Follow button, like on https://twitter.com/Google/followers Using document.getElementsByClassName("user-actions-follow-button js-follow-btn follow-button")[0].innerText correctly displays the text as: Follow ...

Utilizing AJAX to transmit data from an HTML page to a controller in Asp.net

Recently, I started using .net and encountered an issue where I'm attempting to transfer data from a .html file to the controller using AJAX. Here is my ajax call: var dataValue = { ID: 10, Name: 'Test' }; ...

Next.js 13 app directory experiences 404 Not Found error due to dynamic routing issues

I recently built a straightforward to-do app using Next.js 13 paired with TypeScript. The process involved creating an array of objects, each comprising an id string and a name string. Subsequently, I iterated through the list and showcased the names withi ...