JavaScript id= to name= in a form - html

A have a JavaScript that handles localisation.
That gives me a
Position: <input type="text" id="Position1" name="Position1" value="">
This works, and i get the current position on the webpage.
Now, I want to have that position in a form and give it to my SQL by a php script. The php works.
I hva tried:
<input type="hidden" name="poss" id="Position1">
and I know this does not work.
But how do I do it? How do I convert from id= to name= ??
Script:
<script>
window.onload = function(){
var x = document.getElementById('Position1');
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.value = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.value = "" + position.coords.latitude + "," + position.coords.longitude;
}
getLocation();
};
</script>
Position: <input type="text" id="Position1" name="Position1" value="">
<input type="hidden" name="poss" id="Position1">
<input type="submit" style="height:40px;width:350px" />
</form>

try with document.getElementsByName('poss')[0].value = "" + position.coords.latitude + "," + position.coords.longitude; it should work

Related

how do i display website comments above the last posted comment

hi on my website i've a comment box,
everytime i post a comment it get posted below the last comment
my question is: how do i place new comments on top of the old ones.
website: kru.run
This is my full code right now,
<textarea id="title1" type="text " rows="1" cols="15" onkeyup="Allow()" placeholder="username"></textarea>
<textarea id="title" type="text " rows="3" cols="125" onkeyup="Allow()" placeholder="write a comment..."></textarea>
<input type="submit" value="Send" onclick="insert()" style="width:50px;" /></form>
</div>
<div id="display"></div>
<script type="text/javascript">
var titles = [];
var titleInput = document.getElementById("title");
var titleInput1 = document.getElementById("title1");
var messageBox = document.getElementById("display");
function Allow() {
if (!user.title.value.match(/[a-zA-Z]$/) && user.title.value != "") {
user.title.value = "";
alert("Please Enter only alphabets");
}
window.location.reload()
}
function insert() {
titles.push(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
function clearAndShow() {
titleInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += " " + titles.join("<br/> ") + "<br/>";
}
</script>
</div>
</div>
</div>
<br><br>
specifically
i think the insert function is the problem
what can i use instead of push?
function insert () {
titles.push(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
try:
function insert () {
titles.unshift(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
to insert as first item.

Saving information in google sheets from my form

I try to save file on google drive and information in google sheets. But information in Sheets comes like Java.object.
Here is how it looks like in Code.gs :
var FOLDER_ID = '1jxBwrsz0JdBHcADpUUMespe';
var SHEET_ID = '1oJcKQ2RrtxxE1mn_CP-UAHefDxV7zg4';
function doPost(e) {
var data = Utilities.base64Decode(e.parameters.data);
var blob = Utilities.newBlob(data, e.parameters.mimetype, e.parameters.name);
var folder = DriveApp.getFolderById(FOLDER_ID);
var file = folder.createFile(blob);
folder.createFolder(name)
var res = [];
SpreadsheetApp.openById(SHEET_ID).getSheets()[0].appendRow([e.parameters.name, file.getUrl()].concat(res));
return ContentService.createTextOutput("Done.")
}
Here is how it looks like in the HTML file :
<form action="https://script.google.com/macros/s/AKfycbxkzg6ud1VyTI2W4gs-CRJRS3i3qLDXQIGevtyy/exec" id="form" method="post">
<div id="data"></div>
<div class="form-group">
<label for="name">Имя</label>
<input type="text" id='name' name="name" placeholder="Имя" />
</div>
<div class="form-group">
<label for="comment">Комм</label>
<input type="text" name="comment" placeholder="Комментарий" />
</div>
<input name="file" id="uploadfile" type="file">
<input id="submit" type="submit">
</form>
<script>
$('#uploadfile').on("change", function() {
var file = this.files[0];
var fr = new FileReader();
var name = $('#name').value;
fr.fileName = file.name
fr.onload = function(e) {
e.target.result
html = '<input type="hidden" name="data" value="' + e.target.result.replace(/^.*,/, '') + '" >';
html += '<input type="hidden" name="mimetype" value="' + e.target.result.match(/^.*(?=;)/)[0] + '" >';
html += '<input type="hidden" name="filename" value="' + e.target.fileName + '" >';
html += '<input type="hidden" name="name" value="' + name + '" >';
$("#data").empty().append(html);
}
fr.readAsDataURL(file);
});
</script>
Result in Google sheet
How to get data in a readable format?
Personally, I never use forms. Here's an examples that creates 5 text boxes. Validates that you put something into them and returns the code to the server via google.script.run for further processing (i.e. Logger.log the data). I create the html server side and loaded it on the on DOM ready event with JQuery.
Codes.gs
function buildForm(){
var s='';
for(var i=0;i<5;i++){
s+=Utilities.formatString('<br /><input class="jim" type="text" value="" id="%s" />%s',"txt" + i,"text" + Number(i+1));
}
s+='<br /><input type="button" value="Submit" onClick="getValues();" /><input type="button" value="Close" onClick="google.script.host.close();" />';
return s;
}
function saveValues(A){
for(var i=0;i<A.length;i++){
Logger.log('\nid=%s\nvalue=%s',A[i].id,A[i].value);
}
}
function showFormDialog(){
var ui=HtmlService.createHtmlOutputFromFile('form')
SpreadsheetApp.getUi().showModelessDialog(ui,'My Form');
}
form.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(html){$('#form').html(html);})
.buildForm();
});
function getValues(){
var elements=document.getElementsByClassName('jim');
var el=[];
console.log('elements.length=%s',elements.length);
for(var i=0;i<elements.length;i++){
var obj={};
obj['id']='txt' + i;
obj['value']=$('#' + 'txt' + i).val();
el.push(obj);
}
var dataValid=true;
for(var i=0;i<el.length;i++){
console.log('id=%s, value=%s',el[i].id, el[i].value);
if(!el[i].value){
dataValid=false;
$('#'+el[i].id).css('background','#ffff00');
}else{
$('#'+el[i].id).css('background','#ffffff');
}
}
if(dataValid){
google.script.run.saveValues(el);
}else{
alert('Invalid Data Found...Try again sucker....');
}
}
console.log('MyCode');
</script>
<style>
input {margin:5px 5px 0 0;}
</style>
</head>
<body>
<div id="form"></div>
</body>
</html>

Google App Script doesn't set Bcc adress

I have develop a simple google app script to send an email with bcc I just trying to URL param To, From and subject is set is correctly but, the cc and bcc address are not set properly
My code snippet is here.
function doPost(e) { // change to doPost(e) if you are recieving POST data
var mailId = '';
var mailSubject = '';
var mailBody = '';
var htmlBody = '';
var senderName = '';
var replyToAddress = '';
var bccAddresses = '';
mailId = e.parameter['Email'];
mailSubject = e.parameter['Subject'];
mailBody = e.parameter['MailBody'];
htmlBody = e.parameter['HtmlBody'];
senderName = e.parameter['SenderName'];
replyToAddress = e.parameter['ReplyTo'];
bccAddresses = e.parameter['bccAddress'];
Logger.log(':::::::mailId:::::',mailId);
if(mailId != '' && mailId != null){
MailApp.sendEmail({
to:mailId,
subject:mailSubject,
htmlBody:mailBody,
bcc:bccAddresses,
name:senderName,
replyTo:replyToAddress,
});
}
var emailQuotaRemaining = MailApp.getRemainingDailyQuota();
return ContentService
.createTextOutput(emailQuotaRemaining);
}
function doGet(request) {
var emailQuotaRemaining = MailApp.getRemainingDailyQuota();
var result = {
available: 0
};
return ContentService.createTextOutput(
request.parameters.prefix + '(' + emailQuotaRemaining + ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
My HTML code is
<form method="post" style="display:none;" id="form" action="https://script.google.com/macros/s/AKfycbwlMz27gP9vxZA-X58wvxgerhG46A6TEZw33YFe5mvJ0ejFSYQt/exec">
<input type="text" name="Subject" value="Test Subject" />
<input type="text" name="MailBody" value="Test Body" />
<input type="text" name="Email" value="subashc#softsquare.biz" />
<input type="text" name="SenderName" value="MSCB" />
<input type="text" name="ReplyTo" value="test#gmail.com" />
<input type="text" name="bccAddress" value="mscb39#yahoo.com" />
<textarea name="HtmlBody">Test Body</textarea>
<input type="submit" id="sub" />
</form>
<button onclick="subForm();">Submit</button>
<script>
function subForm() {
document.getElementById('form').submit();
}
</script>
Thanks in Advance,
Subash Chandrabose.M
Could you put BCC in the options and test.
MailApp.sendEmail(to, subject, "", {
htmlBody:mailBody,
bcc:bccAddresses,
name:senderName,
replyTo:replyToAddress
});
It seems as though you aren't refrencing a bcc adress when you are calling your function.. How are you calling your function?
(I would comment but I don't have enough reputation yet)

Validation from submitting in Apps Script

Please I need help. I have the same need of this post. I followed the instructions but I can't find my error. I'm frustratred.
When I submit with null fields, the script shows me a blank page.
When I submit with complete fields, the script shows me a blank page also and never upload the file.
This is my final code:
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
form.html
<p>
<form id="myForm" onsubmit="validateForm();">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. </label>
<input type="file" name="myFile">
<input type="submit" value="Submit File" >
<br />
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
Regards,
In the IFRAME mode HTML forms are allowed to submit, but if the form has no action attribute it will submit to a blank page.
The solution suggested by the official documentation is to add the following JavaScript code to prevent all form submitions on load:
<script>
// 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);
</script>
You can also add a return false; or event.preventDefault() at the end of your validateForm() function.

Twitter JSON API with jQuery

function getUsername()
{
var userName = document.form.screen_name.value;
document.getElementById("display").innerHTML = userName;
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
document.getElementById("display2").innerHTML = apiName;
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter.name);
$('#showdata').html("<p>item1="+twitter.follwers_count+" item2="+twitter.friends_count+"</p>");
});
});
Javascript code.
<form method="get" action="#" name="form">
Username: <input type="text" name="screen_name" id="username"/>
<input type="submit" value="submit" onclick="getUsername()" />
</form>
<p>Your username is <h2 id="display"></h2></p>
<p>Your api url is <h2 id="display2"></h2></p>
HTML Code
Whats wrong with this code? The alert comes back undefined.
Thanks
The data comes back as an array. You need to get the object at index 0:
function getUsername()
{
var userName = document.form.screen_name.value;
document.getElementById("display").innerHTML = userName;
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
document.getElementById("display2").innerHTML = apiName;
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter[0].name);
$('#showdata').html("<p>item1=" + twitter[0].follwers_count + " item2=" + twitter[0].friends_count + "</p>");
});
});
}
Of course, you could always just write twitter = twitter[0]; at the start of your function.
Oh, and here's your code jQuery-ified:
function getUsername()
{
var userName = $('[name=screen_name]').val();
$("#display").html(userName);
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
$("#display2").html(apiName);
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter[0].name);
$('#showdata').html("<p>item1=" + twitter[0].follwers_count + " item2=" + twitter[0].friends_count + "</p>");
});
});
}