Tips for storing user input in an array

I have a question about adding data to an array from a table of input boxes. Here's the code I've been working on to achieve this:

Click here to view the code

Whenever I click the add button, I want the data to be stored in the variable named my_data.

The desired output in my variable should look like this:

my_data = [{plank:"1", thickness:"4", width:"6", length:"8", qty:"1", brdFt:"16"}]

If I were to add another set of data, it should append to the variable and result in something like this:

my_data = [{plank:"1", thickness:"4", width:"6", length:"8", qty:"1", brdFt:"16"},
     {plank:"2", thickness:"5", width:"6", length:"2", qty:"1", brdFt:"50"}]

My current code is not efficient, so any help would be appreciated.

Current output: 1, 4, 6, 4, 1

Answer №1

To iterate through all the textboxes, you can use the following code snippet:

function addItem(event) {
    var item = {};

    $('#addItem input[type="text"]')
        .each(function(){item[this.name] = this.value;});
    itemList.push(item);
}

Here, itemList is a global container for your items and #addItem refers to your form.

Check out the updated jsfiddle link.

If you include a form and a submit button, you can also provide a non-JavaScript method for adding information, ensuring accessibility for users with JavaScript disabled.

Answer №2

Check out this modified form for better functionality:

HTML:

<form method="post" action="#" id="add_plank_form">
    <p><label for="plank_number">Plank number</label></p>
    <p><input type="text" name="plank_number" id="plank_number"/></p>

    <p><label for="plank_width">Width</label></p>
    <p><input type="text" name="plank_width" id="plank_width"/></p>

    <p><label for="plank_length">Length</label></p>
    <p><input type="text" name="plank_length" id="plank_length"/></p>

    <p><label for="plank_thickness">Thickness</label></p>
    <p><input type="text" name="plank_thickness" id="plank_thickness"/></p>

    <p><label for="plank_quantity">Quantity</label></p>
    <p><input type="text" name="plank_quantity" id="plank_quantity"/></p>

    <p><input type="submit" value="Add"/></p>
</form>

<p id="add_plank_result"></p>

Javascript:

$(document).ready(function() {

    var plank_data = Array();

    $('#add_plank_form').submit(function() {

        // Data validation
        $('#add_plank_form input[type="text"]').each(function() {
            if(isNaN(parseInt($(this).val()))) {
                return false;
            }
        });

        var added_data = Array();
        added_data.push(parseInt($('#plank_number').val()));
        added_data.push(parseInt($('#plank_width').val()));
        added_data.push(parseInt($('#plank_length').val()));
        added_data.push(parseInt($('#plank_thickness').val()));
        added_data.push(parseInt($('#plank_quantity').val()));

        $('#add_plank_form input[type="text"]').val('');

        plank_data.push(added_data);

        // Compute L x W x F for each plank data
        var computed_values = Array();
        $('#add_plank_result').html('');
        for(var i=0; i<plank_data.length; i++) {
            computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
            $('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
        }

        return false;
    });
});

Answer №3

Loop through each key in my_data and combine the values. (Code is not tested)

const sum = {};

for(let i = 0; i < myData.length; i++) {
  let jsonData = myData[i];
  
  for(let key in jsonData) {
    if(jsonData.hasOwnProperty(key)) {
      if(key in sum) {
        sum[key] += jsonData[key];
      } else {
        sum[key] = jsonData[key];
      }
    }
  }
}

Answer №4

To add elements to a JavaScript array, you can utilize the array push function in JavaScript:

var originalArray = [{item:"apple", quantity:20}, {item:"banana", quantity:15}];

var itemsToAdd = [{item:"orange", quantity:10}, {item:"grape", quantity:12}];

originalArray = originalArray.concat(itemsToAdd);

Answer №5

Apologies, I only briefly looked at the alternative answers.

$(document).ready(function() {
 var data=[];
    var obj = {} 
        $("input").each(function() {
            obj[this.id]=this.value
        });
     alert(obj["plank"])
   data.push(obj)
});

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

Passing parameters in a callback function using $.getJSON in Javascript

I am currently using a $.getJSON call that is working perfectly fine, as demonstrated below. var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?"; $.getJSON(jsonUrl,function(zippy){ ...some code } However, I want to pass a ...

Having trouble with the Post Request feature as an error message pops up saying "unable to post /addstudent/add"

I'm encountering an issue with the post request I'm trying to send. I've attempted to work on it both in Postman and with forms, but I keep getting an error that says "cannot POST /addstudent/add". Below you'll find the code snippets fo ...

What are some strategies for containing elements within a parent div to prevent them from overflowing when new elements are dynamically added

Situation: I am currently working on a project that involves creating a dynamic input box where users can add words that are displayed individually in bubbles. To achieve this, I am attempting to have a div container placed side by side with an input field ...

Exploring the functionalities of the Chrome Web Store with WebdriverJS

I am currently experiencing difficulties when testing the Chrome Webstore with my own node.js script and WebdriverJS. Every time I try to query the results using CSS selectors, I consistently receive "no such element" errors from the WebDriver Server. va ...

Automatically numbering text boxes upon pressing the enter key

Is there a way to automatically number textboxes when I type "1" and hit enter in one of them? For example, if I have 3 textboxes and I type "1" in the first one, can the other textboxes be numbered as 2 and 3 accordingly? <input type="text&qu ...

Reposition div when clicked

I have encountered a challenge where I am unable to perform a small task. My goal is to have the position of "div1" change upon clicking on "div2", taking into account that "div2" is nested inside "div1". Additionally, when clicking on "div2" again, "div1" ...

What is the default delay when utilizing the $timeout function in AngularJS?

While looking at the concise information on the AngularJS $timeout documentation page, I noticed that the 'delay' argument is listed as optional. However, when utilizing $timeout without specifying a delay, I observed that a delay is still implem ...

Arrange Bootstrap-Vue table in a custom order of days (mon, tue, wed) instead of the default

I'm working on a table that populates data from a database using Bootstrap-vue. The database includes a field labeled "day" which contains string values like "mon", "tue", "wed", and so on. I need the table to sort this column by day order rather than ...

Error: The variable "context" has not been defined

I am currently facing an issue while trying to develop a sendNotification function using node.js and Firebase function. I am encountering a problem where I am not receiving any notifications from the sender, and upon checking the Firebase function logs, I ...

How can I access attribute type information in a Node.js Sequelize model?

I have successfully implemented a model in NodeJS using Postgres and sequelize. Let's say the model is Person and it includes fields for name and age. Now, I am looking to dynamically examine the model class to retrieve details about its attributes, s ...

Having trouble retrieving data from nested struct fields

Currently, I am diving into some C code that is not my own in order to learn more about the programming language. However, I've hit a roadblock with a specific part of the code that involves nested structures. Here's the snippet: The Structs: s ...

Creating an Angular JS controller that utilizes a filter for a JSON array of objects

I have the following JSON data and I'm trying to determine the number of objects with Status: 1 in the JSON. The approach I've taken so far is not working. I understand that ng-filter should only be applied to Arrays, but I'm struggling to ...

The issue arises when using Hive Serde with an Array of Structures where the JSON Array is unable to be converted to a Java Object Array

I have built a table: Add jar /../xlibs/hive-json-serde-0.2.jar; CREATE EXTERNAL TABLE SerdeTest (Unique_ID STRING ,MemberID STRING ,Data ARRAY> ) PARTITIONED BY (Pyear INT, Pmonth INT) ROW FORMAT SERDE "org.apache.hadoop.hive.contrib.serd ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

Encountering access violation when excessively calling boost::property_tree::read_json is causing issues

My TCP Server is built using the Boost Asio library version 1.53.0. This server is designed to accept JSON requests and parse them using boost::property_tree::read_json method. To test its reliability, I developed a simple application that creates 128 thr ...

Using ng-repeat can cause conflicts with jQuery function calls

I implemented a combination of AngularJS and MaterializeCSS to display images using ng-repeat. MaterializeCSS comes with a jQuery-based materiabox function that triggers an animation to open a modal for each element with the materialbox class. However, I ...

Firing a custom jQuery event when a page loaded via AJAX is complete, ensuring it is triggered

I am facing an issue with a particular scenario. There is a page that contains a script to load a child page and log a custom event, which is triggered in a Subform. --Index.html-- <body> <input type="button" class="clickable" value="Load child ...

How to adjust a vertex's position after it has been rendered in three.js

Is it possible to update a vertex position after the rendering process? The vertex changes and update statement in the code provided seem to have no impact on the result. Can you please help identify what I might be overlooking here? var mat = new THREE ...

Mongoose issue with updating a field within a subarray object

I'm facing some issues while updating a field in my mongoose model. My intention is to locate a specific username within a list of friends in a user model and then proceed to update a field within the same object that contains the corresponding userna ...

I am unable to utilize the backspace function within a text box generated by JavaScript

I have created a dynamic form using JavaScript that includes buttons and one text input field. However, the issue is that to delete the text entered in the input field, one must highlight the text and then type over it instead of being able to simply use t ...