Capturing HTML form values and storing them in my JavaScript data object

I have a JS object with preset data as shown below in the variable var json. I am trying to create a simple HTML web form where I want the user inputs to be added as a new data set within my initial JS object.

Here is the initial JS object data. The submitted user inputs should populate the values of 'Name, Type, DateModified, and Size' as a new data set within json. However, the challenge lies in getting the input field values to be posted to my JS object as additional data.

var json =[{
            "Name": "zips",
            "Type": "Directory",
            "DateModified": "6/14/2018 17:22:50",
            "Size": "5 KB",
        }, {
            "Name": "presets",
            "Type": "Directory",
            "DateModified": "5/11/2018 7:32:10",
            "Size": "2 KB",
        }, {
            "Name": "workflow",
            "Type": "Non-Directory",
            "DateModified": "6/26/2018 10:29:59",
            "Size": "6 KB",
        },{
            "Name": "software",
            "Type": "Directory",
            "DateModified": "3/16/2018 10:29:59",
            "Size": "16 KB",
        },{
            "Name": "mmm_data",
            "Type": "Directory",
            "DateModified": "6/27/2018 1:19:29",
            "Size": "3 KB",
        }, 
         // i.e. would like new block to populate via web form entry
        {
            "Name": "jobs",
            "Type": "Directory",
            "DateModified": "4/27/2018 11:59:59",
            "Size": "3 KB",
        }, 
         // end area outline
];

The HTML form:

 <div id="addUpload">
            <p>Insert details below for new upload:</p>
            <form id="test" action="#" method="post">
            <div class="form-group">
                <label for="name">Name</label>
                <input class="form-control" type="text" name="name" id="name" />
            </div>
            <div class="form-group">
                <label for="select">Type</label>
                <select name="select" class="form-control">
                    <option value="none" selected="selected">Directory</option>
                    <option value="nonDir">Non-Directory</option>
                </select>

            </div>
            <div class="form-group">
                <label for="email">Date Modified</label>
                <input class="form-control" type="text" name="dateM" id="dateM" />
            </div>
            <div class="form-group">
                <label for="size">Size</label>
                <input class="form-control" type="sized" name="sized" id="sized" />
            </div>
            <p>
                <input type="submit" value="Upload New" class="btn btn-primary btn-block" />
            </p>
        </form> 
        <pre id="output"></pre>
    </div>

Previous attempts that failed:

//    function UploadAdd() {
//        function toJSONString( form ) {
//            var obj = {};
//            var elements = form.querySelectorAll( "input, select, textarea" );
//            for( var i = 0; i < elements.length; ++i ) {
//                var element = elements[i];
//                var name = element.name;
//                var value = element.value;
//
//                if( name ) {
//                    obj[ name ] = value;
//                }
//            }
//
//            return JSON.stringify( obj );
//        }
//
//        document.addEventListener( "DOMContentLoaded", function() {
//            var form = document.getElementById( "test" );
//            var output = document.getElementById( "output" );
//            form.addEventListener( "submit", function( e ) {
//                e.preventDefault();
//                var json = toJSONString( this );
//                output.innerHTML = json;
//
//            }, false);
//
//        });

A visual representation (validation is not the issue, the focus is on handling the post):

https://i.sstatic.net/Qntbl.png

Answer №1

Perhaps this is the solution you're searching for. It involves pushing data to an array upon clicking an event.

var database =[{
            "Name": "files",
            "Type": "Directory",
            "DateModified": "6/14/2018 17:22:50",
            "Size": "5 KB",
        }, {
            "Name": "pictures",
            "Type": "Directory",
            "DateModified": "5/11/2018 7:32:10",
            "Size": "2 KB",
        }, {
            "Name": "documents",
            "Type": "Non-Directory",
            "DateModified": "6/26/2018 10:29:59",
            "Size": "6 KB",
        },{
            "Name": "applications",
            "Type": "Directory",
            "DateModified": "3/16/2018 10:29:59",
            "Size": "16 KB",
        },{
            "Name": "misc_data",
            "Type": "Directory",
            "DateModified": "6/27/2018 1:19:29",
            "Size": "3 KB",
        }, 
         // New block to be populated via web form entry
        {
            "Name": "projects",
            "Type": "Directory",
            "DateModified": "4/27/2018 11:59:59",
            "Size": "3 KB",
        }, 
         // End of outline
];


document.querySelector("#submit").onclick=()=>{
database.push({
Name:document.querySelector("#name").value,
Type:document.querySelector("select").value,
DateModified:dateM.value,
Size:sized.value
});

output.innerText=JSON.stringify(database);

}
<div id="addData">
    <p>Enter details below for new data entry:</p>
    <form id="test" action="#" method="post">
    <div class="form-group">
        <label for="name">Name</label>
        <input class="form-control" type="text" name="name" id="name" />
    </div>
    <div class="form-group">
        <label for="select">Type</label>
        <select name="select" class="form-control">
            <option value="none" selected="selected">Directory</option>
            <option value="nonDir">Non-Directory</option>
        </select>

    </div>
    <div class="form-group">
        <label for="email">Date Modified</label>
        <input class="form-control" type="text" name="dateM" id="dateM" />
    </div>
    <div class="form-group">
        <label for="size">Size</label>
        <input class="form-control" type="sized" name="sized" id="sized" />
    </div>
    <p>
        <input id="submit" type="button" value="Add Data" class="btn btn-primary btn-block" />
    </p>
</form> 
<div id="output"></div>

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

Encountering an Error during the Installation of MapBox SDK in React Native

After creating a React Native project with Expo using expo init MapTry, I encountered an issue while trying to install the MapBox library. Despite following the installation guide at https://github.com/rnmapbox/maps#Installation, I faced an error message w ...

Clicking a link will trigger a page refresh and the loading of a new div

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> $(window).load(function () { var divs = $( #add_new, #details"); $("li a").click(function () { ...

Control and manage AJAX POST requests in the controller

I'm currently working on implementing an ajax post request feature in my project. The goal is to have a button on my html page trigger a javascript event listener, which then initiates an ajax post request to receive some text data. However, I seem to ...

Having trouble with Route Param in React after deploying the application to an Apache server

I am facing an issue with my React app that uses react-router. I have included router params in my Routes, and while it works fine locally, the link with route params is not working once deployed on an Apache server. Can someone assist me in resolving this ...

Mobile compatibility in ECMAScript 5.1 is essential for creating seamless user

Is there a reliable source for information on ECMAScript 5.1 compatibility with mobile browser devices? ...

Laravel Mix causes errors when running `npm run dev` and breaks the package

My nodejs package is built using ES6 features such as 'let', the spread operator (...) and default values for function arguments. However, when I run npm run production with Laravel Mix, an error message appears: ERROR Failed to compile with ...

What is the best way to include an ID parameter in a $ajax GET request?

Real-life Dilemma I've been grappling with an issue for the past 4 hours - I'm attempting to send an http get request with the user ID as a parameter. Despite trying numerous examples found online, I continue to encounter this pesky error on the ...

Is there a way to extract an IPv4 address from a JSON response by navigating through nested values?

Recently, I've delved into learning Ruby and have hit a roadblock. My dilemma lies in trying to search for a specific substring within a JSON response that I've received. The response is structured like the example below: { "00:00:00:CC:00:CC" ...

The Ion slider's onFinish event is triggered when the page loads, independent of any user interaction with the slider

I am facing an issue with ionslider. I have observed that the plugin triggers the onFinish action without any user interaction when the page is loaded. However, on the demo site ionden.com/a/plugins/ion.rangeSlider/demo_interactions.html, the plugin only r ...

Is there JSON data available to determine the overall attendance rate in percentage?

I have a set of attendance data for a specific student. Each subject is marked with a 1 if the student was present, and a 0 if absent on a particular date. I need assistance in calculating the total attendance based on this information... { " ...

Updating a JSON string in PHP by replacing any instances of double quotes

I'm looking to convert a JSON string into an array using PHP, but I'm having trouble escaping double quotes. $string = '["label":"Name","type":"text","placeholder":"Mario","name":"name",*], ["label":"Email","type":"email","placeholder":"< ...

Securing multiple routes in AngularJS using resolve for authentication

How can I authenticate users for all routes in my application without having to specify it individually? Is there a global way to handle authentication for all routes, so that I don't have to include the following code on each $routeProvider.when() c ...

retrieve information provided by the user

When a user inputs a date into #dateUserInput and clicks the button, I want the fetch function to retrieve the appropriate image for that date. However, an error occurs: VM113:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input at getimag ...

Dealing with object properties that may not always be present in Vue.js template tags

Encountering a fatal error TypeError: Cannot read properties of null (reading 'propThatSometimesDoesNotExist') when utilizing the code below: <template> <div> <img v-if="obj.propThatSometimesDoesNotExist" :src=" ...

The select2 does not show the selected information

My select2 is not selecting the value when in edit mode. You can view my data here. Upon clicking the edit data button, it should select "settings" as the parent's value, but unfortunately, it's not working. You can see the issue here. Modal Sc ...

Player script does not contain a valid function signature according to XCDYouTubeKit

I need help finding a regular expression to match these Youtube links. I'm feeling lost and unsure of what to do. https://www.youtube.com/watch?v=2BS3oePljr8 http://www.youtube.com/watch?v=iwGFalTRHDA http://www.youtube.com/watch?v=iwGFalTRHDA& ...

What is the best approach to including files in addition to other data fields when calling a webmethod in asp.net using a jquery ajax request?

My webform contains a variable number of textboxes and dropdowns. To send data to the server-side webmethod, I am utilizing the following code: $.ajax({ type: "POST", url: "SupplierMaster.aspx/RegisterSupplier", data: JSON.stringify({ ...

Properly Adding an External jQuery File in HTML Using jQuery

Seeking assistance as a newcomer to JS and programming in general. Currently working on a website where each page has its own HTML / PHP file, with jQuery and global JS functions included in the footer via a separate includes file "footer.php". Everything ...

The layout option is not specified within the ejs-mate package

error boilerplate I am baffled as to why the layout is not being defined. I have installed ejs-mate and ejs, yet it still gives this error. <% layout('layouts/boilerplate') %> <h1>All campgrounds </h1> <div> <a ...

Does using AJAX with jQuery and PHP guarantee that the response will always be in JSON format?

While working on PHP validation with AJAX requests for user-submitted information, I encountered an issue. The problem arises when attempting to convert the JSON response from PHP to a Javascript object, as it throws the following error: "Uncaught SyntaxE ...