JavaScript data structures used to hold all modified input fields within a document

I am currently working on a project where I have a dynamically generated document using Odoo. The document consists of multiple divs, each containing different types of input boxes such as checkboxes, text fields, and numbers.

Currently, every time a user makes changes to a field, an rpc call is made to the backend to store the new value in the database. However, this process is causing performance issues due to slow client-server communication and delays in writing to the database, especially for a checklist like this one.

Proposed Solution: My idea is to allow the user to make changes to multiple fields before saving them all with a single click of the "Update" button.

Current Challenge: I lack expertise in JavaScript and need guidance on how to implement this feature. One approach I am considering is wrapping all generated rows within a form tag and triggering form submission with form_id.submit() upon clicking the "Update" button. I also aim to find a way to extract and store values from different input fields while doing so.

Are there any more efficient methods to achieve this desired functionality? For instance, instead of immediately storing new data when a field is modified, could I gather information into a structured format (e.g., dictionary, list, or array) and only save it once the user initiates the update process?

EDIT - Proposed Data Structure:

dict = {
    id_line: {key: values, key: values},
    id_line: {key: values, key: values},
    ...
}

Answer №1

To capture values and store them in an array, consider the code snippet below:

var dataToSend = [];
var inputFields = document.querySelectorAll('#myform input');
    inputFields.forEach(function(inputField) {
      switch (inputField.type) {
        case 'text':
        case 'number':
          dataToSend.push({ 
            inputName: inputField.name, value: inputField.value 
          });
          break;
        case 'checkbox':
          dataToSend.push({ 
            inputName: inputField.name, value: inputField.checked
          });
          break;
        default:
          break;
      }
    });

You start by initializing an empty array and selecting all input elements within a form. Based on the type of each input field, you construct an object with its name and value and push it into the array.

The final result after iteration should resemble this structure:

[
  { inputName: '...', value: '...' },
  { inputName: '...', value: '...' },
  { inputName: '...', value: '...' }
]

If there are concerns about NodeList compatibility with forEach method, investigate further using resources such as this post.

Note: Ensure the switch statement covers all possible input types to handle different scenarios effectively.

Alternative approach: In response to a query, storing the data as nested objects instead of an array is achievable with the following implementation:

var dataToSend = {};
var inputFields = document.querySelectorAll('#myform input');
    inputFields.forEach(function(inputField) {
      switch (inputField.type) {
        case 'text':
        case 'number':
          dataToSend[inputField.name] = { 
            inputName: inputField.name, 
            value: inputField.value
          };
          break;
        case 'checkbox':
          dataToSend[inputField.name] = { 
            inputName: inputField.name, 
            value: inputField.value
          };
          break;
        default:
          break;
      }
    });

This technique results in an object structure like this:

{
  someFieldName: {...},
  someFieldName2: {...},
  someFieldName3: {...}
}

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

Creating new form fields dynamically using JavaScript (triggered by onClick event)

I want to dynamically add fields based on user interaction. For instance, when the checkbox or radio button is clicked, additional fields like buttons and textfields should appear. Is it possible to achieve this using onClick? If so, can you please provide ...

Ways to showcase a div exclusively on UC mini browser

I'm looking for help to create a script that will only display a div with the class "info-box" in UC Mini browser. This div should be hidden in all other browsers. Can someone assist me with this? <!doctype html> <html> <head> <m ...

Tips on retrieving the value of a dynamically created control in ASP.NET c# prior to page loading

Is there a way to retrieve the value of a dynamically created control before the page loads in ASP.NET using C#? protected void Page_PreInit(object sender, EventArgs e) { int i = 0; //createDynamicControl(i); var elems = Request.Form.AllKeys.W ...

What is the best way to insert text into a span element within a for loop using JavaScript?

I am currently working on form validation using an array and a loop. In each required field, I have created empty span elements. Here is the JavaScript code that I have set up: var name = document.querySelector('#Name').value, firstLastName = ...

Unable to locate the index.js entry file in React Native

I have a simple React Native application. I am attempting to test it on a virtual Android device by navigating to the project and running npm start -- --reset-cache. After terminating the process, I enter the command react-native run-android. Despite havin ...

React-Select for Creating a Dynamic Multi-Category Dropdown Menu

I am looking to incorporate react-select into my project for a multi-category dropdown list. Specifically, I need the ability to select only one option at most from each category. To better illustrate this requirement, consider the following example wher ...

Tracking ajax calls with piwik: A step-by-step guide

I'm curious about how to enable piwik to track ajax requests. I know there is an API available, but I'm unsure about the exact steps I need to take in order to view ajax loaded pages in the dashboard. Could it be something like this: _paq.push( ...

What is the best way to access and utilize variables passed in an app.post request within another app.post request using Node.js

I have encountered an issue with using const variables in my app.post method. I defined these variables to store user input when submitting a form, but when attempting to send the variables back to the user for verification in my app.post method, it throws ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

Adjust the line spacing in CSS depending on the length of the text

Upon page load, a ul list is dynamically generated via JavaScript. The relevant code snippet is as follows: <ul class="tweet_list"><li class="tweet_first tweet_odd"></li></ul> Related CSS: ​ul.tweet_list li { height: 55px; ...

Socket.io operates individually with each user

Showing a basic web-chat using socket.io. Node.js code: io.on('connection', function(socket) { // Sends 'hello world' message to all users socket.emit('send:message', { text: 'hello world' }); ...

JavaScript interface for touch events

Hi there! I'm wondering if there's a touch phone equivalent of the js onmousemove function (jquery mousemove). It seems like jQuery mobile doesn't have it, and I'm still fairly new to all of this mobile development. /tn ...

When $routeChangeStart is triggered, the location fails to locate the corresponding template

In my web application, I have an app variable associated with the module myApp. There are 3 pages: /login, /registration, and /. The behavior of $routeChangeStart is defined as follows: First, it checks if a global variable user is defined. If yes, it mo ...

What methods can be used to incorporate animation when the display attribute transitions to none?

Is there a way to add animation in a Vue app when replacing elements? I would like the transition from, for example, clicking on a div with 'Num 1' to the divs with class 'showing' not disappear abruptly but smoothly, such as moving to ...

Enhance fullness to facial features

Creating walls by forming faces using specific points is a successful process for me. However, I am now looking to add thickness to these walls, and I am unsure of the best approach. Below is the code I currently use to create the walls: makeWall(start, ...

Typeahead in Angular is failing to function properly after using the $compile method

I have made some adjustments to the popover directive in order to include files and $compile them. While I've managed to make ng-repeats function properly, I'm facing issues when trying to add a typeahead feature. angular.module("app").directive ...

Maintaining the consistent structure of build directories within a Docker container is crucial, especially when compiling TypeScript code that excludes the test

Our application is built using TypeScript and the source code resides in the /src directory. We have tests located in the /tests directory. When we compile the code locally using TSC, the compiled files are deposited into /dist/src and /dist/test respectiv ...

Updating HTML Pages with Dynamic Content

Dealing with a massive project consisting of 50,000 pages (20,000 aspx forms, 10,000 asp forms, and 10,000 html pages) can be overwhelming. With only 2 days to complete the task of adding content after the body tag on all pages, I am seeking advice on ho ...

Access an HTML file in Text Edit on a Mac directly from a web browser

Is there a way to utilize Javascript or another appropriate script to open an HTML file in Text Edit on my Mac? I have created a local web page using Text Edit that has different tabs linking to other Text Edit files within the page. I am looking for a m ...

Warning: Unhandled promise rejection - The type error occurred because the property 'close' of the object is undefined

I am currently configuring node.js in order to test my JavaScript codes using the Jest JavaScript testing framework. Can anyone spot what I might have done incorrectly? package.json file { "name": "institute-jest", "version&quo ...