Convert form input fields of an HTML table to JSON - javascript

I'm currently learning javascript and as an exercice I'm trying to convert an HTML form table to JSON, send it over a communication interface and adding it to another page.
I'm currently able to parse the content of most fields by running through the table with the following code.
function tableToJson(table)
{
var data = [];
var headers = [];
for(var i=0; i<table.rows[0].cells.length; i++)
{
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase();
}
for(var i=1; i<table.rows.length; i++)
{
var tableRow = table.rows[i];
var rowData = {};
for(var j=0; j<tableRow.cells.length; j++)
{
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return JSON.stringify(data);
}
var tables = document.getElementsByTagName("table");
if(tables.length > 0)
{
var json = tableToJson(tables[0]);
console.log(json);
/* Send part bellow */
}
I'm also able to send it through communication once it has been converted and to reimplement it into a new popup from the received JSON.
The problem I'm facing is when some of the fields are input tags with pre-filled values as follow.
<td style="width: 8%; vertical-align: middle; border-top: 1px solid rgba(56, 103, 214, 0.2);">
<input type="number" step="0.01" name="form[18046][amount]" class="form-control">
</td>
The value is not directly available into the cell's innerHTML so the converted JSON data contains the HTML code but not the pre-filled value so when I reimplement the table on the new popup, I have an empty input field.
I would like to be able to get the prefilled value from the innerHTML so I can get rid of the input tag to keep only the value.
Maybe the best way would be to access the value form[18046][amount] through the DOM but I can't find a way to do it.
Does somebody knows how I could get the input prefilled value instead of the cell's innerHTML ?

I've been able to get the pre-filled value by parsing the innerHTML string to retrieve the 'name' attribute value and to ask the DOM the associated value.
var name = tableRow.cells[j].innerHTML.replace(/.*name="([^"]+)".*$/g, "$1");
rowData[headers[j]] = document.getElementsByName(name)[0].value;
I'm still oppened to any other solution, I feel like this ain't the best one at all.

Related

passing value to a different webpage form

I'm trying to learn to make a webapp using JavaScript along side with nodejs. I'm all out of ideas and have no clue if im doing this correctly. So what im trying to do is when a user clicks on a row of a the dynamically created table it opens up a new html page with a bunch of form inputs already filled in with the values in a json. Right now I have it that when I click on the table row I can get the Id chosen and as a test i want to load it in to a input field but im getting it as undefined
a good portion of the table creating function with the fillform function
for (i = 0; i < attendee.length; i++) {
var tr = document.createElement('TR');
if(i % 2 == 0)
{
tr.bgColor = '#E9F2F5';
}
for (var j = 0; j < attendee[i].length; j++) {
var td = document.createElement('TD');
/* if (j != 0) {
td.setAttribute('contenteditable', 'true');
}*/
td.appendChild(document.createTextNode(attendee[i][j]));
tr.appendChild(td);
var currentRow = table.rows[i];
var createClickHandler =
function(tr)
{
return function() {
var cell = tr.getElementsByTagName("td")[0];
var id = cell.innerHTML;
fillForm(id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
tableBody.appendChild(tr);
}
myTableDiv.innerHTML = "";
myTableDiv.appendChild(table);
}
// this function is included in the html page as a onload function
function fillForm(id)
{
window.open("/populatedForm.html");
document.getElementById("id").value = id;
console.log(id);
}
Part of the html input I want to fill out.
<div class=container2>
<form method="PUT" action="/process-form" enctype="multipart/form-data" autocomplete="off">
<fieldset>
<label>
ID<br/>
<input id="id" name="id" type="text" value=" " required/>
</label>
<br/>
This is how my table looks like
And this is how the input looks like when I click on a row in the table. It opens the new html page but the input is set to undefined. I havent done the rest since I cant get id to work.
Any advice would be great! Thank you!
I am going to further answer this down here as it is too long for me to post in the comments.
Once you figure out how to do routing you won't want to do it another way, here is a great resource http://expressjs.com/en/guide/routing.html . Look at the route parameters section.
So what I would do is have a route like /populatedForm/:id. In express it will look something like this.
app.get('/populatedForm/:id', function(req, res) {
res.send(req.params);
});
req.params will grab the id you want to grab, and then where it says res.send() is where you can handle all the business logic from that route. That is where I'd make a call out to the database to grab all the information for that ID, and then send it as a json, then handle the JSON on your front end.
it'd look something like this
app.get('/populatedForm/:id', function(req, res) {
var myJson = getIdAndOtherInfoFromDatabase(req.params);
res.send(myJson);
});
Then you can handle all of it on the front end via JSON. I would google around a bit about this stuff if you get confused or stuck.

Get all form values into javascript array

I am attempting to get all the form values into a normal array[]. I had it working for tags but then I added some tags and can't seem to get it.
With just tags it worked with this
var content = document.querySelectorAll("#form input[name='content[]']");
I am currently trying something like this
var content = document.elements["content[]"].value;
This form can change from user input down the road as each section of the form is a module that they choose to add. It is also important to get the values in order, if that isn't possible then I would need to make it a JSON array. Pure javascript or jquery is fine either way.
Thank you for any help.
EDIT
I used this to solve my problem
var contents=[]
var content = $('#form').serializeArray()
for (var i = 0; i < content.length; i++) {
contents[contents.length]=content[i].value
};
Try
html
<form id="form">
<input type="text" name="content[]" value="abc" />
<textarea name="textarea" value="">123</textarea>
</form>
js
$(function() {
var form = $("#form");
// escape `[]`
var content = form.find("input[name=content\\[\\]]");
// array `literal declaration`
var _arr = [content.prop("value")];
// map all form values to single array
var arr = $.map(form.serializeArray(), function(v, k) {
return [v.value]
});
// array literal with `textarea` `value`
var t = [$("textarea").prop("value")];
console.log(_arr, arr, t);
// _arr: `["abc"]` , arr:`["abc", "123"]` t:`["123"]`
})
Demo.
See Arrays

Javascript unable to extract value of text field in Table

I have a table that has n number of rows and the 8th and the 9th cells are editable test fields. I need to extract the value of these fields using Javascript and HTML DOM. I have tried different methods but whenever I alert it I get &nbsp or nothing at all as the alert content.
Following is the creation statements:
//Input Fields
for(var i=1; i<=mmrows.length-3; i++)
{//mmrows is the source
var input1 =document.createElement('input');
var input2 =document.createElement('input');
input1.setAttribute("type", "Text");
input2.setAttribute("type", "Text");
//input1.id='Inp1'.concat(i);// Tried to assign ID dynamically
//input2.id='Inp2'.concat(i);
input1.id='Inp1';
input2.id='Inp2';
input1.onkeypress=function(){
return isNumberKey(arguments[0]);
}//for validation
var t1=document.createElement("td");
t1.appendChild(input1);
valrows[i+1].cells[8].appendChild(t1);
var t2=document.createElement("td");
t2.appendChild(input2);
valrows[i+1].cells[9].appendChild(t2);
}
I am trying to extract the values in another function and tried the following:
var cells=document.getElementsByTagName('td');
alert(cells.length);
alert(cells[8].innerText);
alert(cells[8].innerHTML);
alert(trim(valrows[i].cells[8].innerHTML));
alert(trim(valrows[i].cells[9].innerHTML));
var str='Inp1'.concat(i);
var str1='Inp2'.concat(i);
alert(document.getElementsById(str).value); //Dynamic ID
alert(document.getElementsById(str1).value);
var tblcells = valrows[i].cells;
alert(tblcells);
for(var j=0; j<tblcells.length; j++)
{
alert(tblcells[j].firstElementChild.value);
} ​
Please tell me what change I need to make inorder to get the text field value.
I have solved this! Actually it was a mistake by myself; i tried accessing the text values by saying getElement(s)ById - no s required.
so i was able to assign 'id's to these text cells dynamically by using the loop variable i and accessing it by getElementById in a similar loop.
Thanks!

Populating form text inputs with data-* data using jQuery

I've been trying to wrap my head around this particular issue for two days now. I feel like I'm close, but I can't crack it. I have a div with data-* attributes:
<div class="pull-right" id="actions" data-ph-title="I am a title" data-ph-type="and a type" data-ph-source="from a source" data-ph-subject="with a subject">
When trying to alert - for instance - the value of "data-ph-title", I can do the following as apparently the dash between "ph" and "title" gets removed.
var info = $("#actions").data();
alert(info.phTitle);
That's great and it works (alerts: "I am a title"), but what I really want is to populate certain form fields with all of this data. I have named my form fields identical to the info object's properties, for example:
<textarea id="placeholder-title" name="phName"></textarea>
I'm trying to come up with a loop that will put all of the info object's property values into the corresponding text inputs (or textareas). This is where I'm getting stuck. I currently have the following code:
var info = $("#actions").data();
$.each(info, function(field, val){
$("[name='" + field + "']").val(val);
});
Any help would be greatly appreciated!
Your code works, so I don't really know what the problem is, aside from you not having a field named 'phName'.
This should be what you need. Iterate through the JSON object and populate the text areas:
var info = $("#actions").data();
for (var key in info) {
if (info.hasOwnProperty(key)) {
$("[name='" + key + "']").val(info[key]);
}
}
Here is a jsFiddle that demonstrates it working.
You don't seem to have a phName in #actions. But what about using an id on your form elements?
var info = $("#actions").data();
$.each(info, function(field, val){
$("#placeholder-" + field).val(val);
});
and
<textarea id="placeholder-phTitle"></textarea>
<textarea id="placeholder-phSource"></textarea>
...
Try this:
var fields = $('#myform input, #myform textarea');
for(var i=0; i < fields.length; i++){
var input = fields[i];
if(info[input.name]) input.value = info[input.name];
}

Dynamically loaded form won't update correctly

I have a form which is loaded into the page using .load(). I want to update the form with the HTML I compute in str, but my code isn't updating the form correctly. Why?
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
});
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
}
You have to put the form modification in the load completion function like this:
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
});
}
The way you were doing it, your code to modify the form was running before the form finished loading so it wouldn't find the content and thus couldn't modify it.
Sorry, I figured i couldnt nest a form within a form. I think thats why it didnt work

Categories

Resources