Transforming dynamic tables into JSON format

Whenever a user adds a new row to the dynamic table to input customer information, I require the data to be submitted in JSON format upon clicking the submit button.

HTML

<table class="table table-bordered table-hover" id="driver">
                <thead>
                    <tr>
                        <th class="text-center text-info">
                            #
                        </th>
                        <th class="text-center text-info">
                            first name
                        </th>
                        <th class="text-center text-info">
                            last name
                        </th>

                        <th class="text-center text-info">
                            mobile num
                        </th>
                        <th class="text-center text-info">
                            email id
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr id='addr0'>
                        <td>
                        1
                        </td>
                        <td>
                        <input type="text" name='firstname'  placeholder='first name' class="form-control"/>
                        </td>
                        <td>
                        <input type="text" name='lastname' placeholder='last name' class="form-control"/>
                        </td>
                        <td>
                        <input type="text" name='mobile' placeholder='mobile number' class="form-control"/>
                        </td>

                        <td>
                        <input type="text" name='email' placeholder='email' class="form-control"/>
                        </td>
                    </tr>
                    <tr id='addr1'></tr>
                </tbody>
            </table>

I am looking to have the JSON data structured in key and value pairs. Any suggestions on how we can achieve this?

[
    {
        "first name": "ashok",
        "last name": "kumar",
        "mobile num": 45,
        "email id": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bec6c7c6fed9d3dfd7d290ddd1d3">[email protected]</a>"
    },
    {
        "first name": "arun",
        "last name": "kumar",
        "mobile num": 789,
        "email id": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0cbd5cde0c1d38ec3cfcd">[email protected]</a>"
    }
]

Answer №1

In order to convert an array of objects into JSON format, you can utilize the serializeArray() function followed by JSON.stringify.

Check out the jQuery documentation here

Description: This method encodes a group of form elements into an array structure containing names and values.

Recent Update

View the live demo here

$("form").submit(function(event) {
  var newFormData = [];
  jQuery('#driver tr:not(:first)').each(function(i) {
    var tb = jQuery(this);
    var obj = {};
    tb.find('input').each(function() {
      obj[this.name] = this.value;
    });
    obj['row'] = i;
    newFormData.push(obj);
  });
  console.log(newFormData);
  document.getElementById('output').innerHTML = JSON.stringify(newFormData);
  event.preventDefault();
});
pre {
  width: 100%;
  background-color: whitesmoke;
  white-space: pre-wrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <table class="table table-bordered table-hover" id="driver">
    <thead>
      <tr>
        <th class="text-center text-info">
          #
        </th>
        <th class="text-center text-info">
          first name
        </th>
        <th class="text-center text-info">
          last name
        </th>

        <th class="text-center text-info">
          mobile num
        </th>
        <th class="text-center text-info">
          email id
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          1
        </td>
        <td>
          <input type="text" name='firstname' placeholder='first name' class="form-control" />
        </td>
        <td>
          <input type="text" name='lastname' placeholder='last name' class="form-control" />
        </td>
        <td>
          <input type="text" name='mobile' placeholder='mobile number' class="form-control" />
        </td>

        <td>
          <input type="text" name='email' placeholder='email' class="form-control" />
        </td>
      </tr>
      <tr>
        <td>
          2
        </td>
        <td>
          <input type="text" name='firstname' placeholder='first name' class="form-control" />
        </td>
        <td>
          <input type="text" name='lastname' placeholder='last name' class="form-control" />
        </td>
        <td>
          <input type="text" name='mobile' placeholder='mobile number' class="form-control" />
        </td>

        <td>
          <input type="text" name='email' placeholder='email' class="form-control" />
        </td>
      </tr>
    </tbody>
  </table>
  <input type="submit" name="g" value="Submit">
  <pre id="output"></pre>
</form>

The code snippet above effectively loops through each row and column of input fields, assigning field names as keys and their respective values as object values within the newFormData array.

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

What is causing my div exchange using .class to fail?

Struggling to convert this code from working with IDs to Classes. The code reveals one Div while hiding another based on the onClick event. Originally, it was straightforward because the div location was absolute. In the classes version, I need to revea ...

Addressing the issue with this.setState and this.state on the Registration page

I am facing an issue with my Registration Page code. I am trying to send data to a database using this.setState and this.state, but every time I run the code, it shows an error in the onSubmit function related to this.state. Can someone please help me unde ...

In Go programming language, modifying the second item in a list will have a direct impact

If you're stuck on what to say, take a closer look at the code and its resulting output. Here's the code snippet: package main import ( "encoding/json" "fmt" ) type Human struct { N string `json:"n"` ...

What steps should I take to display a Modal upon a successful Oauth2 redirect?

I am currently working on an older web application that utilizes the portal/portlet architecture. Within the application, I have a feature that loads in a modal when accessed. The modal includes navigation functionality that allows customers to navigate t ...

Methods for ensuring that fake browser tab focus remains on several tabs simultaneously

Is there a way to simulate multiple tab/window focus in a browser for testing purposes? I need to test pages that require user input and focus on active windows/tabs. Are there any different browsers, plugins, or JavaScript code that can help me achieve th ...

Ways to deactivate the Bootstrap collapse feature

In my accordion FAQs, I am facing an issue where Question 1 is automatically opened when the page loads. Additionally, when I click on Question 2, it closes instead of staying open. I would like to address these problems and make sure that each question st ...

Transferring the "key" and "values" data from a JSON object to a perl script

I am currently working on developing a shopping cart application. All the items stored in the shopping cart are kept within a JavaScript object called Cart, with data structured like {"sku"=quantity}. For instance: Cart={"5x123"=1,"5x125"=3} At this ...

Managing iframes in React using reference methods

Trying to set the content of an iframe within a React component can be a bit tricky. There is a component that contains a handleStatementPrint function which needs to be called when the iframe finishes loading. The goal is to print the loaded iframe conten ...

Which is causing the block: the event loop or the CPU?

example: exports.products = (req, res) => { let el = 1; for (let i = 0; i < 100000000000000; i++) { el += i; } console.log(el); ... ... ... res.redirect('/'); }; If I include a loop like this in my code, which resour ...

Is there a way to use flexbox in a grid to center only a specific tab from MUI?

I am working with an array of tabs and encountering a layout issue. The tabs need to share the available space when there's more than one tab, but when there's only one tab, it should be positioned in the middle of the column. How can I address t ...

Guide to displaying a canvas as an image in a new tab using Reactjs

My current project involves using a canvas barcode generated by the react-barcode library. At the moment, I can only right-click on the canvas to open it as an image in a new tab. Is there a way to achieve this functionality with just a click of a button i ...

Inserting the image of reviewers from the reviews on Google Places

Currently, I have implemented a jQuery plugin on my website to retrieve a single user review from my Google Places account. The plugin can be found at https://github.com/peledies/google-places. While the plugin is functioning correctly for pulling in revi ...

Escape sequences fail to function properly upon being extracted from JSON

I am currently working on developing a straightforward SQL code formatter that extracts the query from a JSON object. My ultimate aim is to copy the final formatted output to the clipboard. However, I have not yet implemented the clipboard functionality as ...

Creating a React functional component that updates state when a specific window breakpoint is reached

Having an issue with my code when it hits the 960px breakpoint. Instead of triggering once, it's firing multiple times causing unexpected behavior. Can someone help me troubleshoot this problem? const mediaQuery = '(max-width: 960px)'; con ...

There was an issue with the specified entry-point "auth0/angular-jwt" as it is missing required dependencies

I am currently working on an Angular project with the following versions: @angular-devkit/architect 0.901.1 @angular-devkit/core 9.1.1 @angular-devkit/schematics 9.1.1 @schematics/angular 9.1.1 @schematics/update 0.901.1 rx ...

Can a Singular Ajax Call be Configured for Multiple Inputs?

Within a PHP file, there is a form tag containing multiple inputs of type submit (essentially buttons) generated automatically by an external PHP script with names like button0, button1, etc. My goal is to utilize AJAX and jQuery to send the value of the c ...

Steps for sending an image to Cloudinary using the fetch API

Struggling to figure out how to successfully upload a file to Cloudinary using fetch on my front-end. After consulting the documentation and various StackOverflow threads, I'm still facing a frustrating 400 error: export async function uploadImageToCl ...

What is the solution for resolving AngularJS URL encoding?

Currently, my AngularJS app utilizes a component known as navbar to house the searchbar along with a search() function. $scope.search = function (keyword) { console.log(keyword); $state.go('main', { keyword: keyword }, ...

JQuery Ajax request functioning smoothly while native JavaScript falls short

I am currently troubleshooting two AJAX calls. One is written in native JavaScript while the other utilizes JQuery to call a PHP script. The jQuery AJAX call seems to be functioning properly, but I am encountering issues with the JavaScript version. Here i ...

Trouble with Bootstrap Modal not closing properly in Chrome and Safari

ISSUE: I'm facing a problem where clicking on the X (font awesome icon) doesn't close the modal popup as expected. https://i.sstatic.net/yXnwA.jpg LIMITED FUNCTIONALITY ON CERTAIN BROWSERS: Currently, the X button for closing the modal works o ...