Fetch HTML Service Values by ID - google-apps-script

In the sample code:
HTML (Index):
<form>
<br><br>
Name:
<br>
<input type="text" name="name">
<br><br>
Comments:
<br>
<input type="text" id="comments">
<br><br>
<input type="button" id="button" value="Submit Info" onclick="google.script.run
.testFunction(this.form)">
</form>
Code:
function doGet() {//Creates the webpage
return HtmlService.createTemplateFromFile('Index')//From the GUI file.
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function testFunction(form){
Logger.log(form.name);//Works when using the 'name' of the element.
Logger.log(form.comments);//Does not work when using the 'ID'.
}
Why does a value get returned when adding the 'Name' of the HTML value, but not the 'ID'? If I want to get the value by ID, how would I do this instead? I've tried:
form.getElementById("comments");
But this just throws me an error, and to be honest I'm out of ideas after that.
Note: It's completely acceptable to me to use the 'name' field, as I have been doing, I'm just curious as I'm brushing up on my HTML.

I believe what Google is doing behind the scenes is extracting the form out as a HTML form and sending it back to the server. HTML forms use the name attribute to store all their name value pairs when sent back to the server. So if this was a get request for this form:
<form>
<input type="text" name="field1" value="value1"/>
<input type="text" name="field2" value="value2"/>
</form>
it would look something like ?field1=value1&field2=value2.
So on the server side in your Code.gs you are basically getting this back as an object (not a DOM object, which is why your form.getElementById("comments"); won't work).
Either way, the standard with <input> tags is to use the name attribute, so you should be sticking with that. The id attribute should really only be used if you need to look up a value in your client side javascript.

Related

Sending additional parameters via form using POST: hidden fields or query parameters

I have some HTML forms and I need to provide additional parameters which the user will not fill up in the form UI. I understand I can do it using query parameters or hidden form fields. Examples :
a form whose data must be submitted to the server together with an option chosen in the previous web page
Ex: URL /createImage?option=option_value (accessible via GET by user) would contain the HTML code below
Query parameter
<form action='/createImage?option=option_value'>
<input type='textfield1' name='var1'>
</form>
Hidden field
<form action='/createImage'>
<input type='hidden' name='option' value='option_value'>
<input type='textfield1' name='var1'>
</form>
(in this case, I suppose a third solution would be to use a HTTP session variable instead)
a fake form used to associate a POST HTTP request with a image.
Query parameter
<form action='/createContainer?image=image1'>
<input type='image' src='container.png'>
</form>
Hidden field
<form action='/createContainer'>
<input type='hidden' name='image' value='image1'>
<input type='image' src='container.png'>
</form>
(in this case, I suppose a third solution would be to use a standard img HTML tag and use Javascript to send the POST request to the server on its click() event)
Are there any upsides/downsides in each one of those approaches or is it just a matter of personal preference?

Formaction attribute is not working when input text has required attribute

I have this code, I use formaction attribute to return in home.html
but it's not working because of required attribute.
<form action="post">
Name:
<input type="text" name="name" required>
<br>
Email:
<input type="email" name="name" required>
<button name="Send" id="send">Send</button>
<button name="Return" id="return" formaction="home.html">Return</button>
</form>
The formaction attribute working fine. I can use the Network tab in my browser's developer tools to observe that when I click Return (in the live demo in your question) the form is submitted to home.html.
The required fields are still required (so I have to fill them in before that happens), but that is to be expected.
It sounds like your goal is to provide an exception and not need the user to enter any data when submitting the form to Return.
That isn't possible without adding a bunch of JS but you're approaching the problem from the wrong angle in the first place.
It looks like you want something for the user to click on that will abort filling in the form and just go to a different URL. There's no data submission involved.
That isn't a job for a submit button.
Use a link instead.
Return
You can apply CSS if you want it to look like a button, but I wouldn't recommend it. The visual appearance of the button implies that the form data will be sent somewhere, and that isn't what you are doing.
You should refer to homepage at the form tag
<form action="home.html" method="POST">
and for the submit
<input type="button" name="Return" id="return">

Input text to link with a form?

I've been working on having a form where a user can input a subreddits name in a input form and be taken to it, but not been working out well. I've tried using get and name="q" but it makes the address funky.
What I have so far:
<form method="post" action="http://www.reddit.com/r/" style="margin-left:5px;margin-right:5px;margin-bottom:0px;">
<input class="form-control" value="" placeholder="Subreddit Name">
</form>
If you're not getting what i'm trying to do: A user types text into an input, the text they typed would be sent to an address as reddit.com/r/(whatever the user typed)
Not knowing from your question whether or not you have access to server-side coding, and based on your answers in the comments, the following should work for you. Note that if a browser has JavaScript disabled, this will bring the user directly to http://www.redit.com/r/
If you have access to server-side scripting, you could add a catch on your server as well to avoid this.
<form method="post" onsubmit="document.location='http://www.reddit.com/r/'+document.getElementById('subredditname').value;return false;" action="http://www.reddit.com/r/" style="margin-left:5px;margin-right:5px;margin-bottom:0px;">
<input id="subredditname" class="form-control" value="" placeholder="Subreddit Name">
</form>
You can do this easily with PHP.
User types text into input field
<input type="text" name="user_text" />
After form submit, run PHP code
$page = $_POST['user_text'];
//send user to website
header('Location: http://reddit.com/r/' . $page);

associating HTML form fields

How do I link multiple input elements in a form so the server knows that two values are related?
Let's assume we have separate fields for first and last names, for multiple people on a single page:
<input name="firstNames" value="John">
<input name="lastNames" value="Smith">
...
<input name="firstNames" value="Jane">
<input name="lastNames" value="Doe">
When POSTing that, the server eventually has the following data:
firstNames = ["John", "Jane"]
lastNames = ["Smith", "Doe"]
So we can determine the respective names by index:
person = firstNames[i] + lastNames[i]
Is there a better way than relying on the order? (Is that even reliable?)
EDIT : This is language specific
Upon further searching, some languages (ASP) allow you to get at the data as a CSV string. So you'll need to add further context to your question. However, the array method still works in all languages.
You can't rely on the order in PHP. If two HTML form elements have the same name the last one overrides everything else (in PHP at least).
Just use arrays.
<input name="firstNames[0]" value="John">
<input name="lastNames[0]" value="Smith">
...
<input name="firstNames[99]" value="Jane">
<input name="lastNames[99]" value="Doe">
You could also use empty [] empty braces as well.
EDIT
Copy paste the code below to see the behavior in PHP.
Down voters : I'd really be interested in knowing where this would not be the case (in a different language)
<html>
<head>
</head>
<body>
<form action='test.php' method='post'>
<input name="firstNames" value="John">
<input name="lastNames" value="Smith">
<input name="firstNames" value="Jane">
<input name="lastNames" value="Doe">
<input type='submit' value='Go'>
</form>
</body>
</html>
<?php
if (!empty($_POST)) {
var_dump($_POST);
}

html button to send email

How do I send an email with specified initial values for the headers subject and message from a button in html, such as this
<form method="post" action="mailto:email.com?subject=subject&message=message">
where subject and message are values fetched from a form?
You can use mailto, here is the HTML code:
<a href="mailto:EMAILADDRESS">
Replace EMAILADDRESS with your email.
This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...
HTML:
<form id="fr1">
<input type="text" id="tb1" />
<input type="text" id="tb2" />
<input type="button" id="bt1" value="click" />
</form>
JavaScript (with jQuery):
$(document).ready(function() {
$('#bt1').click(function() {
$('#fr1').attr('action',
'mailto:test#test.com?subject=' +
$('#tb1').val() + '&body=' + $('#tb2').val());
$('#fr1').submit();
});
});
Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit type, it's just a button type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.
It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.
HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.
As David notes, his suggestion does not actually fulfill the OP's request, which was an email with subject and message. It doesn't work because most, maybe all, combinations of browsers plus e-mail clients do not accept the subject and body attributes of the mailto: URI when supplied as a <form>'s action.
But here's a working example:
HTML (with Bootstrap styles):
<p><input id="subject" type="text" placeholder="type your subject here"
class="form-control"></p>
<p><input id="message" type="text" placeholder="type your message here"
class="form-control"></p>
<p><a id="mail-link" class="btn btn-primary">Create email</a></p>
JavaScript (with jQuery):
<script type="text/javascript">
function loadEvents() {
var mailString;
function updateMailString() {
mailString = '?subject=' + encodeURIComponent($('#subject').val())
+ '&body=' + encodeURIComponent($('#message').val());
$('#mail-link').attr('href', 'mailto:person#email.com' + mailString);
}
$( "#subject" ).focusout(function() { updateMailString(); });
$( "#message" ).focusout(function() { updateMailString(); });
updateMailString();
}
</script>
Notes:
The <form> element with associated action attribute is not used.
The <input> element of type button is also not used.
<a> styled as a button (here using Bootstrap) replaces <input type="button">
focusout() with updateMailString() is necessary because the <a> tag's href attribute does not automatically update when the input fields' values change.
updateMailString() is also called when document is loaded in case the input fields are prepopulated.
Also encodeURIComponent() is used to get characters such as the quotation mark (") across to Outlook.
In this approach, the mailto: URI is supplied (with subject and body attributes) in an a element's href tag. This works in all combinations of browsers and e-mail clients I have tested, which are recent (2015) versions of:
Browsers: Firefox/Win&OSX, Chrome/Win&OSX, IE/Win, Safari/OSX&iOS, Opera/OSX
E-mail clients: Outlook/Win, Mail.app/OSX&iOS, Sparrow/OSX
Bonus tip: In my use cases, I add some contextual text to the e-mail body. More often than not, I want that text to contain line breaks. %0D%0A (carriage return and linefeed) works in my tests.
I couldn't ever find an answer that really satisfied the original question, so I put together a simple free service (PostMail) that allows you to make a standard HTTP POST request to send an email. When you sign up, it provides you with code that you can copy & paste into your website. In this case, you can simply use a form post:
HTML:
<form action="https://postmail.invotes.com/send"
method="post" id="email_form">
<input type="text" name="subject" placeholder="Subject" />
<textarea name="text" placeholder="Message"></textarea>
<!-- replace value with your access token -->
<input type="hidden" name="access_token" value="{your access token}" />
<input type="hidden" name="success_url"
value=".?message=Email+Successfully+Sent%21&isError=0" />
<input type="hidden" name="error_url"
value=".?message=Email+could+not+be+sent.&isError=1" />
<input id="submit_form" type="submit" value="Send" />
</form>
Again, in full disclosure, I created this service because I could not find a suitable answer.
You can not directly send an email with a HTML form. You can however send the form to your web server and then generate the email with a server side program written in e.g. PHP.
The other solution is to create a link as you did with the "mailto:". This will open the local email program from the user. And he/she can then send the pre-populated email.
When you decided how you wanted to do it you can ask another (more specific) question on this site. (Or you can search for a solution somewhere on the internet.)
#user544079
Even though it is very old and irrelevant now, I am replying to help people like me!
it should be like this:
<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">
Here
$emailID,
$MySubject,
$MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):
<form method="post" action="mailto:admin#website.com?subject=New Registration Alert &message= New Registration requires your approval">
You can use an anchor to attempt to open the user's default mail client, prepopulated, with mailto:, but you cannot send the actual email. *Apparently it is possible to do this with a form action as well, but browser support is varied and unreliable, so I do not suggest it.
HTML cannot send mail, you need to use a server side language like php, which is another topic. There are plently of good resources on how to do this here on SO or elsewhere on the internet.
If you are using php, I see SwiftMailer suggested quite a bit.
<form action="mailto:someone#example.com" method="post" enctype="text/plain">
Name:<br>
<input type="text" name="name"><br>
E-mail:<br>
<input type="text" name="mail"><br>
Comment:<br>
<input type="text" name="comment" size="50"><br><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">