Adding or Deleting Rows from Input Table

I'm in the process of creating a website that features an input table allowing users to easily add or remove rows at their discretion. The desired UI is shown below:

https://i.sstatic.net/EFAlM.jpg

Here is the HTML code I have developed so far:

<div class="container my-5">
  <h2>Welcome to dynamic input table with row adding option</h2>
  <form method="" action="">
    <table class="table table-hover my-5">

        <thead class="">
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Pnone Number</th>
                <th>Email</th>
                <th>Remove?</th>
            </tr>
        </thead>

        <tbody>         
          <tr>
            <td>1</td>
            <td><input type="text" name="name-1"></td>
            <td><input type="text" name="phone-1"></td>
            <td><input type="text" name="Email-1"></td>
            <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td>
          </tr>
          <tr>
            <td>2</td>
            <td><input type="text" name="name-2"></td>
            <td><input type="text" name="phone-2"></td>
            <td><input type="text" name="Email-2"></td>
            <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td>
          </tr>
          <tr>
            <td>3</td>
            <td><input type="text" name="name-3"></td>
            <td><input type="text" name="phone-3"></td>
            <td><input type="text" name="Email-3"></td>
            <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td>
          </tr>
          <tr>
            <td>4</td>
            <td><input type="text" name="name-4"></td>
            <td><input type="text" name="phone-4"></td>
            <td><input type="text" name="Email-4"></td>
            <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td>
          </tr>             
        </tbody>

      </table>
      <div class="row m-0">
        <button class="btn btn-warning">Add row</button>
        <button class="btn btn-danger ml-3">Delete last row</button>
        <button type="Submit" class="btn btn-primary ml-auto">Submit</button>
      </div>  
  </form>  
</div>

<head>
    <title></title>

    <!-- media query support -->
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

    <!-- font awsome css link -->   
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

</head>

I am currently seeking guidance on how to effectively implement functionalities for the 'Add row', 'Delete last row' buttons, and the ability to remove rows. These functions should also seamlessly integrate with back-end data processing using Django and MongoDB. Any suggestions on implementing these using frontend JavaScript or handling them dynamically on the backend would be greatly appreciated.

Answer №1

It appears that your question is quite complex and may need to be divided into multiple smaller questions. One approach to deleting rows is by creating a button for users to click on instead of the current method. Additionally, you will need to implement an ajax call to remove the corresponding data from your database. The code provided below is purely for the front-end to visually indicate that a row has been deleted.

$('.my-5 tr').click(function(){
    $(this).remove();
    return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container my-5">
  <h2>Welcome to dynamic input table with row adding option</h2>
  <form method="" action="">
    <table class="table table-hover my-5">

        <thead class="">
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Phone Number</th>
                <th>Email</th>
                <th>Remove?</th>
            </tr>
        </thead>

        <tbody>         
          <tr>
            <td>1</td>
            <td><input type="text" name="name-1"></td>
            <td><input type="text" name="phone-1"></td>
            <td><input type="text" name="Email-1"></td>
            <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td>
          </tr>
          <tr>
            <td>2</td>
            <td><input type="text" name="name-2"></td>
            <td><input type="text" name="phone-2"></td>
            <td><input type="text" name="Email-2"></td>
            <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td>
          </tr>
          <tr>
            <td>3</td>
            <td><input type="text" name="name-3"></td>
            <td><input type="text" name="phone-3"></td>
            <td><input type="text" name="Email-3"></td>
            <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td>
          </tr>
          <tr>
            <td>4</td>
            <td><input type="text" name="name-4"></td>
            <td><input type="text" name="phone-4"></td>
            <td><input type="text" name="Email-4"></td>
            <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td>
          </tr>             
        </tbody>

      </table>
      <div class="row m-0">
        <button class="btn btn-warning">Add row</button>
        <button class="btn btn-danger ml-3">Delete last row</button>
        <button type="Submit" class="btn btn-primary ml-auto">Submit</button>
      </div>  
  </form>  
</div>

Answer №2

If you need the ability to add and delete rows dynamically in a table, you can achieve this through dynamic table creation.

For a demo, you can visit the following link: https://jsbin.com/pewexibole/edit?html,js,console,output

Here is the HTML code snippet:

<!-- HTML code for creating dynamic input table with row adding option -->
<head>
    <title></title>

    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

</head>

<div class="container my-5">
  <h2>Welcome to dynamic input table with row adding option</h2>
    <table class="table table-hover my-5">

        <thead class="">
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Phone Number</th>
                <th>Email</th>
                <th>Remove?</th>
            </tr>
        </thead>

        <tbody>        
        </tbody>

      </table>
      <div class="row m-0">
        <button class="btn btn-warning" onclick="addRow()">Add row</button>
        <button class="btn btn-danger ml-3">Delete last row</button>
        <button type="Submit" class="btn btn-primary ml-auto">Submit</button>
      </div>
</div>

And here is the JavaScript code snippet:

let i = 0;

function rowTemplate(i) {
  return `<tr data-index=${i}>
      <td>${i}</td>
      <td><input type="text" name="name-${i}"></td>
      <td><input type="text" name="phone-${i}"></td>
      <td><input type="text" name="Email-${i}"></td>
      <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;" onclick="removeRow(${i})"></i></td>
    </tr>`
}

for (i = 0; i < 4; i ++) {
  $('tbody').append(rowTemplate(i));
}

function removeRow(i) {
  $("tbody").find(`tr[data-index='${i}']`).remove();
}

function addRow() {
  $('tbody').append(rowTemplate(i));
  i++;
}

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

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...

Executing an AngularJS function using regular JavaScript code

I am currently working with AngularJS and Typescript. I have integrated an external library into my project and now I need to call an AngularJS method from that library, which is written in vanilla JavaScript. I tried following this example, but unfortunat ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

The issue of the Dropdown Menu Not Remaining Fixed While Scrolling

There is a challenge with a Datetime Picker Dropdown Menu not staying in place when the user scrolls. Previous attempts to use .daterangepicker {position: fixed !important;} have been unsuccessful, causing the Datetime Picker to not stay fixed in its posit ...

Use the JavaScript executor to combine a dynamic string

I have a String variable that retrieves IDs from an Excel sheet. String id = formatter.formatCellValue(sheet.getRow(i).getCell(2)); I am trying to dynamically update the ID using JavaScript executor, but it seems that the concatenation is not working cor ...

Unable to locate node module when using Npm.require

I've been attempting to utilize the Npm.require method in order to access the ldapjs module for client authentication. Unfortunately, I'm encountering the following error message: var ldap = Npm.require('ldapjs'); Error: Cannot find ...

Utilizing dynamically assigned ng directives in my unique custom directive

I'm in the process of creating a customized table element that looks like this: <datatable items='tableItems' columns='columnsConfig' /> Here, 'tableItems' represents my array of items and 'columnsConfig&apos ...

When converting to HTML, LibreOffice Writer fails to display footers on even-numbered pages

I'm currently facing an issue with converting my HTML form to PDF using LibreOffice. I need to include a footer in the document, but for some reason, only odd-numbered pages display the footer. Even-numbered pages are not showing anything at all. Int ...

I am having trouble running the code, PHP seems to be operational as I have tested it with sample PHP code. Can anyone help decipher? I have shared the PHP and HTML code for reference

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Computer Status Checker< ...

Error: The connection with mssql in nodejs has been unexpectedly terminated due to a read ECONNRESET issue

I am currently using the node-mssql module which can be found at this link Whenever I try to insert a large amount of data into an MSSQL table, the connection is lost If I attempt to insert more than 4 rows at a time, an error is thrown import * as SQL ...

What is the best way to eliminate the ' from every element in an array in this situation?

My form has hidden fields with values enclosed in single quotes like 'enable'. Using jQuery, I extract these values and push them into an array. This array is then sent to a PHP file using JavaScript through the url attribute of the jQuery AJAX m ...

Looking for assistance with implementing touch gestures on an HTML website?

I am in the process of developing a web application, and I have implemented a menu bar that shifts when a user clicks on an arrow. Each click activates a new menu option. Currently, I am looking to provide users with the ability to swipe over the screen t ...

Creating a mobile-friendly split column layout with Bootstrap 5

I have a similar question to the one posed in this thread How to split Bootstrap column in mobile mode, but I am working with Bootstrap 5 and the previous solution using float: right no longer works due to flexbox. On desktop, I have two columns and I wan ...

Trouble with Sound during Quickblox Webrtc Audio Calls

I am having an issue with my audio calls. When I make a call to another user, everything seems fine except that I cannot hear any sound when speaking into the microphone. I am only interested in making audio calls. The call is initiated by pressing a butt ...

What is the best way to navigate back to the top of the page once a link has been clicked?

One issue I'm facing is that whenever I click on a link in NextJS, it directs me to the middle of the page: <Link href={`/products/${id}`} key={id}> <a> {/* other components */} </a> </Link> I believe the problem l ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

Displaying database values in an array within an HTML format

I need help displaying database values by replacing the $view['time'] with %time% using an array. For example, if $view['time']='8:00 pm';, then when I write %time% it should display 8:00 pm. It works for a single row, but w ...

Can Python be used to personalize a bootstrap template?

There is a bootstrap template that contains several divs, each with specific classes. One of the divs has the class "summary" and I would like to insert text into it using that class. <div class="summary"> <p> </p> </div> ...

Save the content of a string object into an array

I am currently implementing an array sorting functionality using the MVC approach. The array called "array" is used to store values provided at runtime. Within the view, there is a textbox and a button for user input of integer values. Upon clicking the bu ...

Utilize middleware in a separate controller file to handle specific tasks within an Express application

Currently, I have implemented a code snippet that utilizes the express-fileupload middleware for file uploads: const fileUpload = require('express-fileupload'); app.use(fileUpload({useTempFiles: true})); app.post('/upload', (req, re ...