passing value to a different webpage form - javascript

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.

Related

Convert form input fields of an HTML table to JSON

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.

Send both POST and GET in HTML form

I'm trying to make a form that sends submitted data to both email and a .txt file when pressing Submit.
After some research here on Stack Overflow I'm now a bit stuck.
I made a new action in the tag and if the "send-email.php" file name is correct in "new_action.php" only the email function works.
If I have the "send-email.php" incorrect or delete it, the "get-data.php" (using $_GET) works fine.
So yeah, I want both to work.
I guess there's something wrong with the Javascript?
Here's the whole chain:
HTML
<form name="form-name" method="Post" action="new_action.php" id="form-one" onsubmit="process()">
NEW_ACTION.PHP
<?php
include('send-email.php');
include('get-data.php');
?>
JAVASCRIPT
function process() {
var form = document.getElementById('form-one');
var elements = form.elements;
var values = [];
for (var i = 0; i < elements.length; i++)
values.push(encodeURIComponent(elements[i].name) + '=' +
encodeURIComponent(elements[i].value));
form.action += '?' + values.join('&');
}

Display results from api after user input

I'm learning JS and I need some help figuring out why my info isn't getting populated in the html. I'm just trying to get the basic functionality to work, so that I can continue to expand on it.
User is supposed to input a 3 digit route value, which will then return all the route information from an api call. I was able to get the route info to display earlier when I got the api call set up, but I'm struggling to figure why it's not displaying now that I tried adding in a feature to allow the user to input the route. See attached pen
HTML
<div class='container'>
<h1 id='header'>Route Info</h1>
<input id="input" type="text" placeholder="Enter 3 digit route ex 005" >
<input type="button" value="Get Route" onclick="getRoute()">
<br>
<p id = 'p'><span id="routeInfo"></span></p>
</div>
Javascript
$(document).ready(function() {
var route = $('#input');
getRoute.click(function() {
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&callback=myCallback&Route=" + route;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
var myCallback = function(data) {
var myarray = Array.prototype.slice.call(data);
document.getElementById("routeInfo").innerHTML = JSON.stringify(myarray);
}
});
});
It looks like you are jumping through a lot of hoops you don't need to. As long as you are using Jquery, you should look into getting the api data with an ajax request. It's much easier and more intuitive. Also you have a few problems such as trying to get the input value with var route = $('#input'); which return the actual input element. You are also processing the returned data in a way that won't work.
Here's a basic example to get you going on (IMO) a better track:
function getRoute() {
var route = $('#input').val();
var url = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&Route=" + route;
$.ajax({url: url, success: function(data){
var retValue = "";
var i = 0
for(i; i< data.length; i++) {
retValue += data[i].BridgeName + "<br>"
}
document.getElementById("routeInfo").innerHTML = retValue;
}});
}
If you intend functionality in the getRoute.click callback to run, you need to rewrite that as a method function getRoute(), or get the button element via jQuery and assign that to the variable getRoute. As it stands, you have the click method wired via the markup to a function named getRoute which does not exist. In the JS you are trying to register a click event to a jQuery object named getRoute which does not exist.
getRoute needs to be a global function for it to be called from html :
getRoute = (function() {
Also, myCallback needs to be a global function for it to be called from your loaded script (just remove the var):
myCallback = function(data) {

Execute JS in sharepoint display template

In my sharepoint list, I am dealing with items that should have attachments. I customized the template so that it would allow me to add attachments, but I see no possibilities to mark attachments as mandatory. I managed to check for attachments with the script
<script type="text/javascript" language="javascript">
function PreSaveAction()
{
var elm = document.getElementById("idAttachmentsTable");
if (elm == null || elm.rows.length == 0)
{
document.getElementById("idAttachmentsRow").style.display=&apos;none&apos;;
alert("Please attach Documents");
return false ;
}
else { return true ;}
}
</script>
but I was only able to use it in a custom form (not the template). Since the template is used for pretty much any interaction with the list, I want to use it and would like to execute the js code after the template has loaded. The template is referenced in between the tags <ZoneTemplate> and </ZoneTemplate>. There's much more code inside that form, but sharepoint-designer won't let me edit anything apart the stuff between those two tags.
It's really frustrating, because I seem to miss an obvious point. Hope I delivered enough information as I am not used to work with sharepoint and it's forms and templates for them...
When you need to add a JavaScript to a list form, you can browse to the form directly. For example, if your list is called MyList, then the new item form would be at http://url/Lists/MyList/newform.aspx and the edit form would be at EditForm.aspx. Browse to the page or pages where you want to insert your javascript code, then under Site Actions, click Edit Page. Add a Content Editor Web Part and either insert the javascript directly into the HTML of the content editor web part or add a link to an HTML file that has the javascript.
As for marking an attachment as mandatory, you may just need to include some wording to the form that will instruct the user to click Attach File button. Maybe something like this that would add a row to the bottom of the form table
<script type="text/javascript">
function addRow() {
var required = document.createTextNode("*");
var table = document.getElementsByClassName("ms-formtable")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var tr = document.createElement("tr");
var td1 = document.createElement("td");
td1.setAttribute("class","ms-formlabel");
td1.setAttribute("vAlign","top");
var h31 = document.createElement("h3");
h31.setAttribute("class","ms-standardheader");
var text1 = document.createTextNode("Attachment");
h31.appendChild(text1);
var span1 = document.createElement("span")
span1.setAttribute("class","ms-formvalidation");
span1.setAttribute("title","This is a required field");
span1.appendChild(required);
h31.appendChild(span1);
var td1.appendChild(h31);
var tr.appendChild(td1);
var td2 = document.createElement("td");
td2.setAttribute("class","ms-formbody");
td2.setAttribute("vAlign","top");
var text2 = document.createTextNode("Click the Attach File button in the ribbon to add an attachment");
var td2.appendChild(text2);
var tr.appendChild(td2);
var tbody.appendChild(tr);
}
</script>
This is pretty ugly and can be simplified with jQuery.
<script type="text/javascript">
function addRow() {
var h3 = $('<h3 class="ms-standardheader">Attachment</h3>').append('<span class="ms-formvalidation">*</span>');
var td1 = $("<td></td>").append(h3);
var td2 = $("<td>Click the Attach File button in the ribbon to add an attachment</td>");
var tr = $("<tr></tr>").append(td1);
$(tr).append(td2);
$(".ms-formtable").first().find("tbody").first().append(tr);
}
</script>
Keep in mind this is untested and probably has some bugs in it.

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