How can I get text from a user using Google Spreadsheet? - javascript

I am trying to create an automatic mailing system for a Google Spreadsheet.
I want to create a menu button that the user can press and get a dialog box with a big (paragraph-size) textbox to write his message in.
My problem is creating the right instance to be able to pass the user text input:
I tried using Browser.inputBox("title"), but this only generates a 1-line text box.
I tried using the SpreadsheetApp.getUi().prompt method, but again this only generates a 1-line text box.
Any ideas on what class/method I should be using to be able to get the user's text message?
EDIT
here is another go, this time using shoeModalDialog() and html code.
i think its pretty close, but not working yet. Thoughts?
function showDialog() {
var html = HtmlService.createHtmlOutputFromFile('testHTML')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(600)
.setHeight(400);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Dialog title');
}
function jsGetText(text) {
//do something with the string object
}
<script>
function mySuccessFunction(textBox) {
jsGetText(textBox.value)
}
</script>
<form method="post" >
<textarea name="textBox" id="textBox" cols="60" rows="20" class="html-text-box"></textarea><br>
<input type="submit" value="send" class="html-text-box" onclick="google.script.run.withSuccessHandler(mySuccessFunction).withUserObject(document.getElementById('textBox')); google.script.host.close()">
<input type="reset" value="cancel" class="html-text-box" onclick="google.script.host.close()">
</form>

The showDialog function looks good. Don't put all the code into the onClick() attribute. Remove method="post" from the form tag. You don't want to send a POST request in this situation. Use Logger.log() statements, and console.log() statements, and constantly be checking the Execution Logs for server errors.
Code.gs
function jsGetText(text) {
Logger.log('text: ' + text);
Logger.log('text.length: ' + text.length);
for (var key in text) {
Logger.log('key: ' + key);
Logger.log('value: ' + text[key]);
};
var objFieldOne = text['textBox'];
Logger.log('objFieldOne: ' + objFieldOne);
//do something with the string object
return objFieldOne;
};
testHTML.html
<script>
function fncGetUserTxt() {
var objUsrInput = document.getElementById('idInputForm');
/* for (var key in objUsrInput) {
console.log('key: ' + key);
console.log('value: ' + objUsrInput[key]);
};
*/
google.script.run
.withSuccessHandler(mySuccessFunction)
.jsGetText(objUsrInput);
//google.script.host.close()
};
function mySuccessFunction(textBox) {
alert('Success! : ' + textBox);
};
</script>
<form id='idInputForm'>
<textarea name="textBox" id="textBox" cols="60" rows="20" class="html-text-box"></textarea><br>
<input type="submit" value="send" class="html-text-box" onmouseup='fncGetUserTxt()'>
<input type="reset" value="cancel" class="html-text-box" onclick="google.script.host.close()">
</form>

Related

Why does appending a textarea only work with .text and not .val?

Slowly working up my javascript and jquery skills right now and I had been attempting to reset a textarea with .val('') and found that I could not append to it after I had reset it.
var console = $('#console');
function Initialize(data){
console.text(data);
};
function AddText(data){
console.append(data);
};
function clearConsole(){
console.val('');
};
Now if I change console.text(data) to console.val(data) then I cannot append at all, rather I can only set the value. Now I also know there are more methods of getting the text from the textarea, such as .value(), but I haven't messed around with that much because I got my code working by using .text('') instead of .val('')
But I ran into some really strange behavior that is easier to just show instead of type out a description:
var ta, tb, tc;
$(document).ready(function() {
ta = $('#ta');
tb = $('#tb');
tc = $('#tc');
});
//first textarea
function AddText() {
if (ta.text()) {
ta.append(Math.random() + "\n");
} else {
ta.text(Math.random() + "\n");
}
};
function ClearText() {
ta.text('');
}
//second textarea
function AddVal() {
tb.append(Math.random() + "\n");
};
function ClearVal() {
tb.val('');
}
//third textarea
function AddVal2() {
if (tc.val()) {
tc.append(Math.random() + "\n");
alert('Append is being called, but not appending.');
} else {
tc.val(Math.random() + "\n");
}
};
function ClearVal2() {
tc.val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<p> Using .text to initialize the textarea allows .append and clearing</p>
<textarea readonly cols=50 rows=5 placeholder="First textarea : A" id="ta"></textarea>
<br>
<button type="button" id="AddText" onclick="AddText()">Add Text</button>
<button type="button" id="ClearText" onclick="ClearText()">Clear</button>
<br>
<p>Using .val to initialize the textarea does not allow .append after clearing</p>
<textarea readonly cols=50 rows=5 placeholder="Second textarea : B" id="tb"></textarea>
<br>
<button type="button" id="AddVal" onclick="AddVal()">Add Text</button>
<button type="button" id="ClearVal" onclick="ClearVal()">Clear</button>
<br>
<p>Using .val to initialize the textarea with the extra checks doesn't append at all.
<br>An alert is generated to show the append is called, but no appending occurs.</p>
<textarea readonly cols=50 rows=5 placeholder="Third textarea : C" id="tc"></textarea>
<br>
<button type="button" id="AddVal2" onclick="AddVal2()">Add Text</button>
<button type="button" id="ClearVal2" onclick="ClearVal2()">Clear</button>
Can someone explain to me this behavior and the best practice to use? Or is it all really the same and it's just up to preference? Thanks.
EDIT: Bonus jfiddle
I don't know why .append isn't allowed after .val but you shouldn't be using .append. .append is for appending elements not text.
.text is for setting the innerHTML and escaping that HTML so that it appears as plain text.
.val is what you should be using, even for textareas.
To append with .val, just do
$el.val($el.val() + "\nnew content");
Also, it should be noted that your choice of variable name, console, will hide the global variable by the same name (lets you log to your F12 Developer Tools).
Your appends are working, you just aren't seeing them because of a weird quirk. The quirk is that append sets the text property but if you clear the val the text will no longer be visible.
You can see this for yourself by adding console.log(tb.text(), tb.val()) to AddVal(). Adding similar logs to the other functions may be helpful as well.
The really interesting question here is why does it work that way, and that I'm afraid I'll have to leave to someone with deeper knowledge.
input is an html field with a single value:
<input value='whatever' />
but textarea has content:
<textarea>this is the content that can be added to</textarea>
So loosely think that textarea is a block of text which can be added to, input is a variable which can be defined

Putting input field text into variable and using that for jquery JSON get request

Hey so I am pretty much a jquery/javascript noob and im trying to create a simple search box where it returns movie data from the OMDB API. Sadly I don't think its passing the input data along correctly so I feel I am doing something wrong when passing the input text into a variable because its not passing along anything I put into my form field. Does anyone know where I am going wrong here?
Here is my code so far:
function getSearchResult() {
var search = document.getElementById("title").innerHTML;
jQuery.getJSON("http://www.omdbapi.com/?t=" + search + "=json", function(result) {
jQuery.each(result, function(i, field) {
jQuery("div").append(field + " ");
});
});
};
<form id="searchForm">
Search for movie:
<input type="text" name=movie_title id="title">
<input type="button" value="Submit" onClick="getSearchResult()">
</form>
You made a few mistakes in your code :
to get the value of an input use :
var search = document.getElementById("title").value;
instead of innerHTML
Then, the url you use to call the API is wrong, check the documentation before using : http://www.omdbapi.com/
use this url :
"http://www.omdbapi.com/?t=" + search + "&y=&plot=short&r=json"
Complete Code
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.2.2.min.js"></script>
<script>
$(function() {
$('#search').on('click', function() {
var search = document.getElementById("title").value;
$.getJSON(
"http://www.omdbapi.com/?t=" + search + "&y=&plot=short&r=json",
function(result) {
$.each(result, function(i, field){
$("body").append(field + " ");
});
}
);
});
});
</script>
</head>
<body>
Search for movie:<input type="text" name="movie_title" id="title" />
<input type="button" id="search" value="Submit" />
</body>
</html>
You have a bit of an odd hybrid of vanilla JS and jQuery going on there; consider changing your approach to fully utilize the tools that jQuery puts at your disposal. Please find code below that might help point you in that direction (note the updates to the HTML and the attachment of onClick to the button itself):
JS:
$('#searchForm input[type="button"]').on('click', function(){
var search = $('#searchForm input').text();
var searchResult = $('#searchResult'); //save reference to DOM object
$.getJSON("https://www.omdbapi.com/?t=" + search + "=json", function(response){
console.log(response);
searchResult.empty();
if(response.Response === 'False') {
searchResult.append('<p>'+response.Error+'</p>');
} else {
$.each(result, function(i, field){
searchResult.append('<p>'+field+'</p>');
});
}
});
});
HTML:
<form id="searchForm">
Search for movie:<input type="text" name=movie_title id="title">
<input type="button" value="Submit" >
</form>
<div id="searchResult"></div>
You can run it here (although none of my quick searches returned a result, so I can't verify the success condition):
https://jsfiddle.net/wct58tco/

Validate textarea in html with java script

I'm trying to prevent users from inputting and submitting single quotes ( ' ) into the textarea. below is what I have, but it isn't work.
<script>
function valtxtarea() {
var val = document.getElementById('textarea').value;
if ('\''.test(val)) {
alert('do not add single qoutes to your inputs!');
}
}
</script>
<form>
enter text below
<textarea>input contents here</textarea>
<input type="button" onclick="valtxtarea();" value="send">
</form>
You missed the id attribute as well as the regex isn't valid
function valtxtarea() {
var val = document.getElementById('textarea').value;
if (/\'/.test(val)) {
alert('do not add single qoutes to your inputs!');
}
}
<form>
enter text below
<textarea id="textarea"></textarea>
<input type="button" onclick="valtxtarea();" value="send">
</form>
Better yet, why not prevent them from even typing it?
<form>
enter text below
<textarea id='inputText' oninput="valtxtarea();"></textarea>
<input type="button" value="send">
</form>
<script>
var oldValue = "input contents here";
document.getElementById('inputText').value = oldValue;
function valtxtarea() {
var textArea = document.getElementById('inputText');
if (textArea.value.match(/.*\'.*/g)) {
textArea.value = oldValue;
} else {
oldValue = textArea.value;
}
}
</script>
With this every time they type a char it is check and if it contains a ' then it sets it back to the old value. You could easily expand it to include other characters you do not want to allow.
var val = document.getElementById('textarea').value;
There is no HTML element with the id textarea.
Do something like this:
<textarea id="textarea">input contents here</textarea>
Also you probably want to prevent form submission if there is a validation error, so put return false; in the if in valtxtarea() and put return valtxtarea() in the onclick.

Create mailto from form with custom fields

I have a HTML form with 3 fields (Name, E-Mail and Message) and I want to create a custom mailto with this 3 fields but I don't want create a fixed content like this:
Send a mail
Is this possible? If it isn't, do I have another way to do a simple formulary? My page is a landing page and only have HTML, CSS and some JavaScript (Bootstrap too).
--- Edit ---
I found this, for example: http://www.techrepublic.com/article/set-up-an-html-mailto-form-without-a-back-end-script/
But it write too much information in the body, the result is literal:
Name=Your name
E-mail=mail#company.com
Comment=Testing textarea
Submit=Submit
I can answer myself, after a deep search I could fix my problem.
JavaScript:
function sendMail() {
var name = $('#contact #name').val();
var email = $('#contact #email').val();
var message = $('#contact textarea').val();
window.location.href = 'mailto:mail#company.com?subject=The subject - ' + name + ' (' + email + ')' + '&body=' + message;
};
HTML:
<form>
<input type="text" id="name" name="name" >
<input type="email" id="email" name="email">
<textarea rows="5"></textarea>
</form>
<button type="submit" class="btn btn-primary" onclick="sendMail()">Button Text</button>
We can't use a submit input, because window.location.href doesn't work with it; we need to use a button who will run a function.
And it's all, very simple :)

how do i get the info from a form using javascript?

i have a form which user enters some data, could be checkboxes, radio buttons, textfields, etc
when user click submit button, i want to refresh the page with whatever data that was entered
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
</head>
<body id="ref">
<form>
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
</form>
<input type="button" onclick="c()" value="submit">
<script type="text/javascript">
function c()
{
var o = document.getElementById('ref');
o.innerHTML = '';
var n = document.createElement('p');
var nam = document.getElementById('name');
n.innerHTML = "Your name is: " + nam;
o.appendChild(n);
var a = document.createElement('p');
var ag = document.getElementById('age');
a.innerHTML = "Your age is: " + ag;
o.appendChild(a);
//how do i get the info from the form? because both nam and ag are coming up null
}
</script>
</body>
</html>
my guess this is not working is because the page refreshes then tries to fetch the element by id which is not there anymore.. whats the correct way of doing this??
You're confusing objects with their properties. Here, you're getting the HTMLInputElement instance for the "age" field:
var ag = document.getElementById('age');
But here you're using that object as though it were a simple value:
a.innerHTML = "Your age is: " + ag;
The HTMLInputElement object has a value field you can use for that:
a.innerHTML = "Your age is: " + ag.value;
Separately, you're completely destroying the page by doing this:
var o = document.getElementById('ref');
o.innerHTML = '';
...because you've given the body element the ID "ref". Completely replacing the body element completely replaces the body element, so you can't rely on objects that only exist as subordinates of that element.
The usual thing is to have an element to fill in, and (optionally) to remove the elements you no longer need. For instance (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
<div id="result">
</div>
(Note I moved the button into the form for convenience.)
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result = document.getElementById("result");
form.parentNode.removeChild(form);
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
}
There, when the button is pressed, I remove the form and fill in the "result" div.
You could add the "result" div dynamically if you wanted (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
You can access the fields using a briefer and somewhat more natural syntax if you change your id values to name values instead (live copy):
HTML:
<form name="theForm">
Please enter your name:<input type="text" name="name" />
Please enter your age:<input type="text" name="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.theForm,
nameField = form.name,
ageField = form.age,
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
Further reading:
DOM2 Core (well-supported by most modern browsers)
DOM2 HTML
DOM3 Core (increasingly supported)
If you want to update your html using java-script only , you may use ".value" attribute of the input;
var a = document.createElement('p').value;
var ag = document.getElementById('age').value;
Usually the Form information is processed using server-side code , this is done by specifying the action attribute of the form:
<form action="processuserinfo.aspx">
...
</form>
I'm pretty sure this isn't doable javascript alone. You'll need to use a server-side language like php. Try to google php forms, and you should get some good results. :)

Categories