Guide to logging form entries into a JSON object using plain JavaScript

Is there a way to include manual inputs and manually selected options in the JSON object being logged from the form inputs? Currently, they are not appearing in the logged JSON object. Any suggestions on how to rectify this issue would be greatly appreciated. Thank you!

let kitForm = document.querySelector("#kitForm"),
  formData = new FormData(kitForm),
  submitButton = document.querySelector("#submitButton");

function onSubmit(e) {
  e.preventDefault();

  let jsonObject = {};

  for (const [key, value] of formData) {
    jsonObject[key] = value;
  }
  console.log(JSON.stringify(jsonObject));
}

submitButton.addEventListener("click", onSubmit);
<form id="kitForm">

  <label for="kitName">Kit name:</label>
  <input id="kitName" type="text" name="kitName">

  <label for="applicationName">Application:</label>
  <select id="applicationName" type="text" name="applicationName">
    <option>Application 1</option>
    <option>Application 2</option>
  </select>

  <label for="tradeName">Trade:</label>
  <select id="tradeName" type="text" name="tradeName">
    <option>Value 1</option>
    <option>Value 2</option>
  </select>

  <label for="description">Description:</label>
  <input id="description" type="text" name="description">

  <input id="submitButton" type="submit" value="Submit">
</form>

Answer №1

Utilize a form array serializer method.

Take a look at this demonstration:

let kitForm = document.querySelector("#kitForm"),
  formData = new FormData(kitForm),
  submitButton = document.querySelector("#submitButton");

function onSubmit(e) {
  e.preventDefault();
  console.log(serializeArray(kitForm));
}

submitButton.addEventListener("click", onSubmit);


function serializeArray(form) {
    var serialized = [];
    for (var i = 0; i < form.elements.length; i++) {
        var field = form.elements[i];
        if (!field.name || field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') continue;
        if (field.type === 'select-multiple') {
            for (var n = 0; n < field.options.length; n++) {
                if (!field.options[n].selected) continue;
                serialized.push({
                    name: field.name,
                    value: field.options[n].value
                });
            }
        }
        else if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) {
            serialized.push({
                name: field.name,
                value: field.value
            });
        }
    }

    return serialized;
};
<form id="kitForm">

      <label for="kitName">Kit name:</label>
      <input id="kitName" type="text" name="kitName">

      <label for="applicationName">Application:</label>
      <select id="applicationName" type="text" name="applicationName">
        <option>Application 1</option>
        <option>Application 2</option>
      </select>

      <label for="tradeName">Trade:</label>
      <select id="tradeName" type="text" name="tradeName">
        <option>Value 1</option>
        <option>Value 2</option>
      </select>

      <label for="description">Description:</label>
      <input id="description" type="text" name="description">

    <input id="submitButton" type="submit" value="Submit">
</form>

source code:

Answer №2

To improve your code, consider placing the formData declaration within the submit function.

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

Retrieving object information in the constructor using Angular and Typescript

When attempting to access an object's data within a constructor, it results in an "undefined" object. Even though it functions properly in the ngOnInit() function, the data which is about to be reset is required every time the component is initiated. ...

How do I send events between router view components in Vue.js?

I'm currently developing an e-commerce platform utilizing vue.js with a backend API. The root component is named Main.vue, consisting of a navigation section using router-link and a main content area displayed by router-view. Within the Cart.vue rout ...

Transmit data in JSON format using jQuery's AJAX function

What could be causing the PHP not to retrieve my links array? function check_links() { $matches = $this->input->get('links'); if($matches == true) { echo json_encode('matches is true'); } el ...

There are no platform-specific files for Android or iOS within the React Native project directory

I meticulously followed the React Native Official Documentation step by step, starting from https://facebook.github.io/react-native/docs/getting-started.html and successfully initialized a project, obtaining all the necessary files apart from splash.js a ...

Image carousel with variable height

I'm attempting to implement a slide show of images with previous and next functionality. When the user clicks "previous," I want the images to slide to the left, and when they click "next," I want the images to slide to the right with a 0.5 second del ...

javascript is failing to display the appropriate message at the correct moment

Wrote a code to handle the type of message I should get, looping over all the rows in the table to find matching conditions. These are my conditions: - If all rows have data-mode="success" and data-pure="yes", it's correct and successful. - If any row ...

Using Backbone for the front end and Node.js for the backend, this website combines powerful technologies

Currently, I am in the process of developing a new website that will function as a single-page application featuring dialog/modal windows. My intention is to utilize Backbone for the frontend and establish communication with the backend through ajax/webs ...

What steps should I take when dealing with two dynamic variables in a mediator script within the WSO2 ESB?

I'm facing an issue with my if condition - it doesn't work properly when the value is static. However, when I make `annee2` and `annee1` static (for example =2019), it works fine. Here's the code snippet: <script language="js"&g ...

Evolving the appearance of every vacant element

Currently, I am working on a project that allows users to add items. To facilitate this process, I have included an "add another" button which enables them to include additional items all at once. In order to validate the form and save values to the datab ...

Bring in camera from gltf

Can someone provide guidance on utilizing a camera from gltf within three-js? I am currently implementing the gltf loader as demonstrated in this example. ...

Using Node.js with Express, the Router.use() method expects a middleware function as an argument, however, it received a different type: ' +

As I delve into the world of back-end development using node and express, my current project involves creating a back-end for a simple blog with posts and user authentication. This will be utilized later in an angular 4 application. While testing the "Pos ...

I require the ability to access a reference parameter with a dynamically changing name within a Vue template

<div v-for="x in 4" :class="(images[x] === null) ? 'not-removable' : 'removable'" class="img-container"> <input style="display: none" type="file" ...

Remove a specific item from a MongoDB Collection using its ID

I have a MongoDB collection named "Members" which stores data for each member including first name, last name, and an autogenerated Object ID. I am able to retrieve the data using ExpressJS and display it with VueJS. While my get and post methods are worki ...

Processing JSON in PHP to retrieve data

I'm trying to figure out how to parse JSON data using PHP. Here is a basic example: $myJSON_string = '{ "features": [{ "type": "Feature", "geometry": { "type": "Point", "coordinates": ...

Executing a <SCRIPT> within an Ajax-loaded webpage

Utilizing Framework7 for my web application has been great since it allows me to load pages using Ajax, giving it an app-like feel. However, I am facing a challenge with making the "ad" code display properly on Ajax-loaded pages. If you inspect the ad co ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

How can I display milliseconds from a date in Angular2+?

I recently encountered an issue while working with a custom pipe that was used to display time. I attempted to modify it so that it could also show milliseconds: {{log.LogDate|jsonDate|date:'dd.MM.yyyy &nbsp; HH:mm:ss.sss'}} Here is the cod ...

What methods are available to create distinctive, shareable links akin to those utilized by Zoom and Google Hangouts?

I'm currently developing a group video chat app and I'm facing the challenge of generating distinct shareable links for every chat room created. Can anyone guide me on how to accomplish this? My aim is for users to easily join the chat room when ...

Guide on updating a variable to the following string within an array

Snippet: months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October&apos ...

Issue with mobile device view: BS custom dropdown toggle not functioning

Built a Bootstrap dropdown navbar with custom jQuery & CSS, but facing an issue with toggling submenu in Mobile devices. See the code snippet below: $('.dropdown').click(function() { $(this).children('.dm-lv1').toggleClass('s ...