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):