How to acquire information from form in javascript? - html

Hey guys i was wondering how to acquire information from form in javascript and i found the method with object forms, but i doesnt want to work(returns undefined), because object is undefined. Do you know what i am doing wrong in that, could you attach some explanations? I know what it is possible to do it by getElement function,but i would like to understand why this solution doesn't work.
Regards!
<script type="text/javascript">
function cos(sth){
var par = document.getElementById("para1");
par.style.color = 'blue';
par.style.fontSize="30px";
par.style.fontFamily="Impact,Charcoal,sans-serif";
}
function getFormValue(){
document.write(5+6);
var doc = document.forms["myForm"]["email"].value;
// OR
var doc = document.forms[0].elements["name"];
document.write(doc);
}
</script>
</head>
<body>
<p id ="para1">JavaScript Exercises - w3resource</p>
<div>
<button onclick="cos();">Style</button>
</div>
<form name="myForm">
<input type="text" name="email"/>
<button onclick="getFormValue()">
</form>
</body>
</html>

document.write(5+6);
var doc = document.forms["myForm"]["email"].value;
Since the page has loaded, the document is in a closed state.
Calling document.write implicitly calls document.open which creates a new document.
You then write 11 to this document.
Next you try to get the form element. It doesn't exist in this new document.
Then you try to get the email field from it. Since you don't have a form, you get an error.
If you fix that:
var doc = document.forms["myForm"]["email"].value;
// OR
var doc = document.forms[0].elements["name"];
document.write(doc);
You read the value of the email field and assign it to doc.
Then you overwrite it with elements["name"].
There is no form control called name, so you get undefined.
var doc = document.forms["myForm"]["email"].value;
document.write(doc);
… works fine. You just need to remove the junk you put around it to break it.

Related

Submit a form with a hidden field that is a var from a calculation

I have a var that is the result of a math calculation which changes based on the users input. I'm trying to create a get-form in html that will send the results to a new page.
my result appears on the page as var newpayment
document.querySelectorAll("#cart span.newpayment")[0].innerHTML = newpayment.toFixed(2);
However the form does not show the result..
<form id="form1" method="get">
<input type="hidden" id="submit_total1" value=""
name="submit_total1">
<button id="select1">Select</button>
</form>
<script>
var form = document.getElementById("form1");
document.getElementById("form1").action = "/complete/file.php";
document.getElementById("select1").addEventListener("click", function ()
{
var submit_total1=newpayment;
form.submit();
});
</script>
Thanks for your help but I'm still not able to get it to work. I've also tried another method by setting the value after the form is rendered (see Below). The var "newpayment" is displayed on the page as the span class but it will not populate as the value in the form. Thank you in advance for any remedies.
`
<script>
function setVal(){
document.getElementById('id').value=newpayment;
}
</script>
<p >$<span class="newpayment">0.00</span></p>`

UI to HTML, conversion will not write a date to the sheet

I am trying to replicate a question posed by Pieter Jaspers regarding a conversion of a form from UIApp to HTML. The original question is:
Original question by Pieter Jaspars answered by Sandy Good
If I replicate the code exactly I get the correct result, but when I try to recreate my inline form and amalgamate the two I am not getting a result. The inline form question is here:
HTML inline form formatting question answered by Mogsdad
The code I have so far is in the requisite number of parts, a form and two .gs sheets. I have checked for spelling mistakes and I have tried editing out each line to see what and where I get, but with my limited experience I am drawing a blank. The only minor success is if I run the function InsertInSS() from within the code editor. This posts the word "undefined" in the correct cell in the correct spreadsheet, but not the date as I am trying to do!
Form:
<!-- Use a templated HTML printing scriptlet to import common stylesheet. -->
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
<html>
<body>
<div>
<!-- Page header title & 'completion warning -->
<span class="grey"><b>ProReactive Log Form v3.0.74</b></span>
<h4>Complete ALL fields to ensure the form is processed successfully</h4>
<div class="block">
<!-- First input box created -->
<div class="inline form-group">
<label form="date">Date</label>
<input type="date" id="date" style="width: 125px;">
</div>
</div>
</div>
<!-- End of fields for completion, finish form with submission button -->
<button class="share" onclick="runGoogleScript()">submit</button>
</body>
</html>
<script>
function onSuccess(argReturnValue){
alert('was successful ' +argReturnValue);
//ResetFields on Screen
Document.getElementById("date").value = "";
}
function runGoogleScript() {
logger.log('v3.0.74 ran!');
var inputValue = document.getElementById("date").value;
google.script.run.withSuccessHandler(onSuccess)
.InsertInSS(inputValue);
};
</script>
The Code.gs:
function doGet(e) {
return HtmlService.createTemplateFromFile('myForm')
.evaluate()
.setTitle('ProReactiveLog')
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
};
and the seperate.gs:
function InsertInSS(argPassedInName) {
var ssKey = '1cZuEMDrIyzIFm4lGCT20s-Wpv27o0hbbZAsxD1WJFL8';
var SS = SpreadsheetApp.openById(ssKey);
var Sheet = SS.getSheetByName('LOG');
Sheet.getRange(Sheet.getLastRow()+1,1,1).setValue(argPassedInName);
}
Any ideas where I am going wrong? All help as ever, greatly appreciated.
An Apps script HTML App, will not allow a date object to be passed to the server.
google.script.run Parameter Documentation
The documentation states:
Requests fail if you attempt to pass a Date, Function, DOM element besides a form, or other prohibited type, including prohibited types inside objects or arrays.
You will need to pass the date as a string. Convert the date to a string in client side code, and convert it back to a date, if need be, in the server code. However, even if you set the value in the spreadsheet as a string, it may get coerced back into a date without you needing to do anything. Especially if you have that column defined as a date in the spreadsheet.

HtmlService form submit opens new tab with foo bar URL

I am attempting to build a UI for a spreadsheet using GAS HtmlService. The HTML below is a very simple form with a single text box that pulls a value ("Kristina") from the sheet, successfully. However, when I try to submit the form a new tab is opened in Chrome that attempts to open the URL "bffc95ee-ff64-4d2c-xxxx-19d9824eb4b4.foo.bar/?fname=Kristina" with "xxxx" replacing more random letters and numbers (just in case). At no point do I use the words "foo.bar" in my code, so I'm pretty sure that that part isn't coming from me. It does not change each time or after logging out and back in. I'm getting the same result on two different computers.
<html>
<body>
<div>
<form id="formtest1">
<label>First Name</label>
<input name="fname" type="text" maxlength="255" value="<?= fname ?>"/>
<input type="submit" value="Submit"
onclick="google.script.run.processForm(document.getElementById('formtest1'));
google.script.host.close()"/>
</form>
</div>
</body>
</html>
The above is being displayed using the following function:
function htmltest(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sht = ss.getActiveSheet();
var html = HtmlService.createTemplateFromFile("HTML");
html.fname = sht.getRange(2, 3).getValue();
ss.show(html.evaluate());
};
If I understand correctly, the "google.script.run.processForm(...)" script in the HTML should trigger the following function, as set up in the projects triggers:
function onFormSubmit(){
Browser.msgBox("Test");
};
But it doesn't appear to do so as the form doesn't close and the msgBox doesn't appear. Only the foo bar URL in a new tab.
Hopefully I've explained the issue clearly and am not making an embarrassing mistake.
You cannot use a real "submit" button with google.script.run (this is a documented restriction in the user guide). Change it to "button" and it should work fine.
The project trigger onFormSubmit() will be triggered by a submission via the Forms Service. There is no relationship between this trigger and your HTML code; they are two different ways to interact with users.
An html forms pattern is shown in the HTML Service documentation here, and the script below is an adaptation of it.
Code.gs
The only real change from your original is that onFormSubmit() has been replaced with processForm(form), which includes a parameter, for the object that will be passed from the html code.
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "htmltest",
functionName : "htmltest"
}];
sheet.addMenu("Custom Menu", entries);
};
function htmltest(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sht = ss.getActiveSheet();
var html = HtmlService.createTemplateFromFile("HTML");
html.fname = sht.getRange(2, 3).getValue();
//Logger.log( html.getCodeWithComments() );
ss.show(html.evaluate());
};
function processForm(form){
var fname = form.fname;
Browser.msgBox("Test - " + fname);
};
HTML.html
This is a modification of your original, echoing the pattern from the documentation. The form submission SuccessHandler is a one-liner, which closes the dialog. Once it completes, the server-side function is invoked with the form content, retrieved using this.parentNode (to refer to the form).
There are other ways - see Get value of html text box in Apps Script function for a different approach.
<html>
<script type="text/javascript">
// SuccessHandler to close form
function close() {google.script.host.close();}
</script>
<body>
<div>
<form>
<label>First Name</label>
<input name="fname" type="text" maxlength="255" value="<?= fname ?>"/>
<input type="button" value="Submit" onclick="google.script.run
.withSuccessHandler(close)
.processForm(this.parentNode)"/>
</form>
</div>
</body>
</html>
Just add this to your script tag on your html file.
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
Source: HTML Service: Communicate with Server Functions

How to get data into html checkbox list, taken from javascript function call

I have a page which assign some values to arrays when a function named 'hndlr' is called.code of the file is given bellow
<html>
<head>
<title>Search Example</title>
</head>
<body>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
// here I assign values to arrays pageName,pageLink,pageDetails using a for loop
}
// Some codes (I cant change anything in here)
// call the function hndlr here (I cant change anything in here)
</script>
</body>
</html>
I want to take pageName array into a checkbox list and pass the pageLink of selected checkboxes to another file.
I tried using bellow code just before the end of the body tag. but it isn't passing any data to next page(b.php)
<form action="b.php" method="post">
<script>
for (var j = 0; j < 5; j++) {
document.write("<input type='checkbox' name='formDoor[]' id='"+j+"' value= '' />"+pageName[j]+"<br />");
document.getElementById(j).value = pageLink[j];
}
</script>
<input type="submit" name="formSubmit" value="Submit" />
</form>
When I print the output, It displays 'undefined' strings just before the check boxes.
That means pageName[j] doesn't return any value.
problem is, these arrays are not visible to second part(part I tried with check boxes)
Please show me the way to do this..
Weird, your code is working for me (click the code box to show it): http://codepad.viper-7.com/4IVobE
You can't submit the form on this site but you can see that the arrays are accessible within the second script tag. I also tried it on my local server and after submitting the form I was able to access the values in b.php just fine.

Google CSE open in new window

I would like to integrate the Google Search bar into my site, and using the default code by Google CSE I have:
<div id="cse-search-form" style="width: 100%;">Loading</div>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function() {
var customSearchOptions = {};
var imageSearchOptions = {};
imageSearchOptions['layout'] = google.search.ImageSearch.LAYOUT_POPUP;
customSearchOptions['enableImageSearch'] = true;
customSearchOptions['imageSearchOptions'] = imageSearchOptions;
var customSearchControl = new google.search.CustomSearchControl(
'003243520079760326318:WMX-1462312306', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setSearchFormRoot('cse-search-form');
options.setAutoComplete(true);
customSearchControl.draw('shop.htm/cse', options);
}, true);
Followed by the style and the </div>
But I do not want the results to open on the same page, I want them to open in searchresults.htm which has the container div
<div id="cse" style="width:100%;"></div>
if I put in this form:
<form action="http://www.amberantiques.com/searchresults.htm" id="cse-search-box">
<fieldset style="border:none;">
<input type="hidden" name="cx" value="003243520079760326318:WMX-1462312306" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" size="31" />
<input type="submit" name="sa" value="Search" />
</fieldset>
</form>
Then the form sends it to the page but doesnt run the search, but if you then use the Google bar on the page, it runs the search fine.
Basically, how do you get the google bar to open the results page?
Cheers
If you upgrade to the latest Google Code V2 then you can achieve this by editing code you paste to show results.
<gcse:search></gcse:search>
Change this to
<gcse:search linktarget="_parent"></gcse:search>
When you're building the code for your Google CSE, one of the Look and Feel options is "Two Page" - which will allow you to search on one page, and display the results on another.
The V2 code for the Custom Search (free) or Site Search (paid) gives you a range of options for searching and displaying results on the same page or having it's own result page.
By default this WILL open all result links in a new tab or window.
I had the issue where I needed the search results to open on the same tab/window.
I adjusted the following code
<gcse:search></gcse:search>
to this
<gcse:search linktarget="_self"></gcse:search>
I guess if for some reason your default behavior is not opening in a new tab/window and you need it to then you could try the following
<gcse:search linktarget="_blank"></gcse:search>
Hope this helps.
Can you test by putting this code?
options.enableSearchboxOnly("http://www.amberantiques.com/searchresults.htm");
between this line
var options = new google.search.DrawOptions();
and this line
options.setSearchFormRoot('cse-search-form');
Then put the following code in searchresults.htm
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
function parseQueryFromUrl() {
var queryParamName = "q";
var search = window.location.search.substr(1);
var parts = search.split('&');
for (var i = 0; i < parts.length; i++) {
var keyvaluepair = parts[i].split('=');
if (decodeURIComponent(keyvaluepair[0]) == queryParamName) {
return decodeURIComponent(keyvaluepair[1].replace(/\+/g, ' '));
}
}
return '';
}
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function () {
var customSearchControl = new google.search.CustomSearchControl(
'003243520079760326318:WMX-1462312306', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
var queryFromUrl = parseQueryFromUrl();
if (queryFromUrl) {
customSearchControl.execute(queryFromUrl);
}
}, true);
</script>
If this doesn't work you can simply read the documentation provided by google. You'll get your desired information in Designing the Look and Feel with the Control Panel section. Or you may find it in Designing the Look and Feel with XML section. I think you are looking for two page layout.
Another option is to go to http://www.google.com/cse/manage/all and then use the control panel there to customize your search engine as you desire.
Building on the code above, you could use:
<gcse:search newWindow="true"></gcse:search>
According to Google's documentation.
Not obvious from looking at the Google documentation (a familiar story) but you can do this very simply using the v2 Custom Search code by selecting the 'Results only' option in the 'Look and Feel' section:
Click 'Save and Get Code' and paste into your searchresults.htm page.
You now just need to create a simple search box that points to that page which you can put in your page header.
e.g.
<form action="http://www.amberantiques.com/searchresults.htm">
<input type="search" name="q"/>
<input type="submit" value="Go"/>
</form>