Already tried everything from different references but, I can't get it to work. I intended to use it for google photo submission form. I just want my text inputs and textarea to clear after it successfully uploaded everything.
Here's the whole HTML code.
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName"
placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection"
placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
<br>
<br>
<div id="output"></div>
<script>
var rootFolderId = 'xxxxxxxxxxxxxxxxxxx';
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function uploadFiles() {
var allFiles = document.getElementById('filesToUpload').files;
var applicantName = document.getElementById('applicantName').value;
if (!applicantName) {
window.alert('Missing applicant name!');
}
var gradesection = document.getElementById('gradesection').value;
if (!gradesection) {
window.alert('Missing Grade & Section!');
}
var folderName = applicantName + ' - ' + gradesection;
if (allFiles.length == 0) {
window.alert('No file selected!');
} else {
numUploads.total = allFiles.length;
google.script.run.withSuccessHandler(function(r) {
// send files after the folder is created...
for (var i = 0; i < allFiles.length; i++) {
// Send each file at a time
uploadFile(allFiles[i], r.folderId);
}
}).createFolder(rootFolderId, folderName);
}
}
function uploadFile(file, folderId) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
document.getElementById('output').innerHTML = 'uploading '
+ file.name + '...';
//window.alert('uploading ' + file.name + '...');
google.script.run.withSuccessHandler(onFileUploaded)
.uploadFile(content, file.name, folderId);
}
reader.readAsDataURL(file);
}
function onFileUploaded(r) {
numUploads.done++;
document.getElementById('output').innerHTML = 'uploaded '
+ r.fileName + ' (' + numUploads.done + '/'
+ numUploads.total + ' files).';
if (numUploads.done == numUploads.total) {
document.getElementById('output').innerHTML = 'All of the '
+ numUploads.total + ' files are uploaded';
numUploads.done = 0;
}
}
</script>
The form upload and displays the response to the user.
I want to reset the form so, the form resets to its original state, so when the user upload another file it wont upload the same file again. Right now, the submission message stays and I have no clue on how to reset the form.
I am new to javascript and I have no clue on what to call to rest the form, any idea? TIA Guys :)
As your code snippet only contains input, You can find all inputs using querySelectorAll and reset its value.
Example below. When you click the button it resets all the input.
function resetAllInput() {
const allInput = document.querySelectorAll('input');
allInput.forEach( input => {
input.value = "";
})
}
function uploadFiles() {
console.log('uploading files');
resetAllInput();
console.log('Resetted all inputs');
}
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName" placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection" placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
You can assign null value to your input element:
const reset = () => {
let fileInput = document.getElementById('file-input');
fileInput.value = null;
}
<input type="file" id="file-input">
<button onclick="reset()">Reset</button>
Related
I'm trying to make a custom web form where people can upload their resume and license to my Google Drive. I found some code online, which I've modified a little, and it sort of works.
code.gs
var emailTo= "test#test.com"
function doPost(e) {
try {
var data = e.parameter.fileContent; // First attachment
var filename = e.parameter.filename; // First attachment filename
var data2 = e.parameter.fileContent2; // Second attachment
var filename2 = e.parameter.filename2; // Second attachment filename
var email = e.parameter.Email;
var name = e.parameter.Name;
var result=uploadFileToGoogleDrive(data,filename,data2,filename2,name,email,e);
return ContentService // return json success results
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(result) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": error}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('Form').setSandboxMode(
HtmlService.SandboxMode.IFRAME);
}
// new property service GLOBAL
var SCRIPT_PROP = PropertiesService.getScriptProperties();
// see: https://developers.google.com/apps-script/reference/properties/
/**
* select the sheet
*/
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
/**
* record_data inserts the data received from the html form submission
* e is the data received from the POST
*/
function record_data(e,fileUrl,fileUrl2) {
try {
var doc = SpreadsheetApp.openById("Spreadsheet ID");
var sheet = doc.getSheetByName('Responses'); // select the responses sheet
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [ new Date() ]; // first element in the row should always be a timestamp
// loop through the header columns
for (var i = 1; i < headers.length; i++) { // start at 1 to avoid Timestamp column
if(headers[i].length > 0 && headers[i] == "Resume") {
row.push(fileUrl); // add data to row
}
else if(headers[i].length > 0 && headers[i] == "License") {
row.push(fileUrl2); // add data to row
}
else if(headers[i].length > 0) {
row.push(e.parameter[headers[i]]); // add data to row
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
}
catch(error) {
Logger.log(e);
}
finally {
return;
}
}
function uploadFileToGoogleDrive(data, file, data2, file2, name, email,e) {
try {
var dropbox = "Application Test";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var contentType = data.substring(5,data.indexOf(';')),
bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),
blob = Utilities.newBlob(bytes, contentType, file);
var subfolder = folder.createFolder([name, email].join("-"));
var file = subfolder.createFile(blob);
var fileUrl=file.getUrl();
var contentType2 = data2.substring(5,data2.indexOf(';')),
bytes2 = Utilities.base64Decode(data2.substr(data2.indexOf('base64,')+7)),
blob2 = Utilities.newBlob(bytes2, contentType2, file2);
var file2 = subfolder.createFile(blob2);
var fileUrl2=file2.getUrl();
//Generating Email Body
var html =
'<body>' +
'<h2> New Application </h2>' +
'<p>Name : '+e.parameters.Name+'</p>' +
'<p>Email : '+e.parameters.Email+'</p>' +
'<p>Phone Number : '+e.parameters.Phone+'</p>' +
'<p>Address : '+e.parameters.Address+'</p>' +
'<p>Postal Code : '+e.parameters.Postal+'</p>' +
'<p>File Name : '+e.parameters.filename+'</p>' +
'<p><a href='+file.getUrl()+'>Resume Link</a></p><br />' +
'<p>File Name : '+e.parameters.filename2+'</p>' +
'<p><a href='+file2.getUrl()+'>License</a></p><br />' +
'</body>';
record_data(e,fileUrl,fileUrl2);
MailApp.sendEmail(emailTo, "New Application Recieved","New Application Request Recieved",{htmlBody:html});
return file.getUrl() + file2.getUrl();
} catch (f) {
return ContentService // return json success results
.createTextOutput(
JSON.stringify({"result":"file upload failed",
"data": JSON.stringify(f) }))
.setMimeType(ContentService.MimeType.JSON);
}
}
Form.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="uploadForm" action="Insert Web App URL" method="POST">
<input type="hidden" value="" name="fileContent" id="fileContent">
<input type="hidden" value="" name="filename" id="filename">
<input type="hidden" value="" name="fileContent2" id="fileContent2">
<input type="hidden" value="" name="filename2" id="filename2">
<label> Name : </label><input required type="text" value="" name="Name" id="Name"><br><br>
<label> Email : </label> <input required type="text" value="" name="Email" id="Email"><br><br>
<label> Phone Number : </label><input required type="text" value="" name="Phone" id="Phone"><br><br>
<label> Address : </label> <input required type="text" value="" name="Address" id="Address"><br><br>
<label> Postal Code : </label><input type="text" value="" name="Postal" id="Postal"><br><br>
</form>
<label> Resume: <input id="Resume" name="Resume" type="file"/>
<label> License: <input id="License" name="License" type="file"/><br><br>
<input value="Submit" type="button" onclick="UploadFile();" />
<script>
function UploadFile() {
var reader = new FileReader();
var file = document.getElementById('Resume').files[0];
var reader2 = new FileReader();
var file2 = document.getElementById('License').files[0];
reader.onload = function(){
document.getElementById('fileContent').value=reader.result;
document.getElementById('filename').value=file.name;
//document.getElementById('uploadForm').submit();
}
reader2.onload = function(){
document.getElementById('fileContent2').value=reader2.result;
document.getElementById('filename2').value=file2.name;
document.getElementById('uploadForm').submit();
}
reader.readAsDataURL(file);
reader2.readAsDataURL(file2);
}
</script>
</body>
</html>
Usually it'll only upload one of the files (the license), and show a blank untitled file for the other, although it does upload both files correctly every few attempts.
I am creating a score keeping app and need to save the name of the players and the game name in local storage, have no idea how to apply it to the code I have
$(document).ready(function() {
$("#add-playername").click(function(e) {
e.preventDefault();
var numberOfPlayernames = $("#form1").find("input[name^='data[playername]']").length;
var label = '<label for="data[playername][' + numberOfPlayernames + ']">Playername ' + (numberOfPlayernames + 1) + '</label> ';
var input = '<input type="text" name="data[playername][' + numberOfPlayernames + ']" id="data[playername][' + numberOfPlayernames + ']" />';
var removeButton = '<button class="remove-playername">Remove</button>';
var html = "<div class='playername'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-playername").before(html);
});
});
$(document).on("click", ".remove-playername", function(e) {
e.preventDefault();
$(this).parents(".playername").remove(); //remove playername is connected to this
$("#form1").find("label[for^='data[playername]']").each(function() {
$(this).html("Playername " + ($(this).parents('.playername').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form2" method="post">
<div class="gamename">
<label><b>Enter Game Name</b></label>
<input type="text" name="game name" placeholder="Game Name" id="user_input">
</div>
</form>
<form id="form1" method="post">
<div class="playername">
<label for="data[playername][0]">Add Player Name</label>
<input type="text" name="data[playername][0]" placeholder="Enter player's name" id="data[playername][0]" />
</div>
<button id="add-playername">Add Player</button>
<br>
<br>
<input type="submit" value="Submit" />
</form>
Grab game and players using the jquery selector on form submit by preventing the form using jquery
Prepare object for the game and players
Convert the object to a string using the JSON.stringify( your_data_object) function
Save to localStorage using localStorage.setItem( 'key' , 'value' ) function
<script>
$('#form1').submit(function(){
var game_name = $("#form2 #user_input").val();
var players = [];
var players_inputs = $("#form1").find("input[name^='data[playername]']");
$.each(players_inputs, function(){
var player = $(this).val();
players.push(player);
});
var data = {
game_name : game_name,
players: players
}
console.log(data);
// save to localstorage
localStorage.setItem('game_players', JSON.stringify(data) );
event.preventDefault();
});
</script>
late to answer but something like this
<input type="submit" value="Submit" id="btn_submit" />
<script type="text/javascript">
$(document).ready(function(){
$("#btn_submit").click(function(e){
e.preventDefault();
var jsonObj = [];
players = {}
count = 0;
$('input[type=text]').each(function(){
if($.trim($(this).val()) && ($(this).attr('name').indexOf("playername") >= 0)){
players[count++] = $(this).val()
}
});
players['game_name'] = $("#user_input").val();
jsonObj.push(players);
console.log(jsonObj);
var jsonString= JSON.stringify(jsonObj);
localStorage.setItem("jsonString", jsonString);
/* remove localstorage */
// localStorage.removeItem("jsonString");
/* get localstorage */
// console.log(localStorage.getItem("jsonString"));
});
</script>
I am trying to separate some JS code that is embedded in to a HTML file. I do not own this code, it is for a remote support landing page but I'm not sure how to separate them out.
I have tried copying the JS code in to a different .js file and then adding the script tags to link but no luck.
<script type="text/javascript" src="https://www.islonline.net/webapi/api.js?
libs=join"></script>
<div class="isl-connect-form">
<form id="isl-connect-form" action="#" method="get" onsubmit="return
isl_connect();">
<fieldset>
<legend>Enter your session code and click Connect</legend>
<div>
<label for="isl-code-field">Session code</label>
<input type="text" name="code" id="isl-code-field" value="" />
</div>
<input type="submit" name="submit" value="Connect" />
</fieldset>
</form>
<div id="isl-feedback"></div>
</div>
<script type="text/javascript">
function isl_connect() {
var doc = document,
f = doc.getElementById('isl-connect-form'),
r = doc.getElementById('isl-feedback'),
is_msie = navigator.userAgent.indexOf('MSIE') >= 0,
b = null;
ISLOnline.Join.getSessionInfoByCode(
f.code.value,
function (info) {
r.className = 'isl-success';
r.innerHTML = 'Connecting to session ' +
info.getAttribute('sessionCode');
if (is_msie) {
r.innerHTML += ', please click the button below:<br />';
r.appendChild(doc.createElement('br'));
var b = doc.createElement('input');
b.type = 'button';
b.name = 'join';
b.value = 'Start';
b.onclick = function () {
info.join();
};
r.appendChild(b);
} else {
info.join();
}
},
function (error) {
r.className = 'isl-error';
r.innerHTML = 'Invalid session code!';
/* comment the line above and uncomment the line below if you
wish to
display the error that is sent by the server */
//r.innerHTML += error.getDescription();
}
);
return false;
}
Create a new JS file and put the original full javascript within it then load it after the islonline.net API call. I have shown an example.
<script type="text/javascript" src="https://www.islonline.net/webapi/api.js?libs=join"></script>
<div class="isl-connect-form">
<form id="isl-connect-form">
<fieldset>
<legend>Enter your session code and click Connect</legend>
<div>
<label for="isl-code-field">Session code</label>
<input type="text" name="code" id="isl-code-field" value="" />
</div>
<input type="submit" name="submit" value="Connect" />
</fieldset>
</form>
<div id="isl-feedback"></div>
</div>
<!-- your new external JS file -->
<script type="text/javascript" src="https://www.example.com/path/to/your/file.js"></script>
Your new Javascript file will contain the original JS code, with a slight modification to help separate HTML and JavaScript by using addEventListener instead of onsubmit:
document.getElementById('isl-connect-form').addEventListener('submit', function isl_connect(event) {
if (typeof event.preventDefault == 'function') event.preventDefault();
var doc = document,
f = this,
r = doc.getElementById('isl-feedback'),
is_msie = navigator.userAgent.indexOf('MSIE') >= 0,
b = null;
ISLOnline.Join.getSessionInfoByCode(
f.code.value,
function (info) {
r.className = 'isl-success';
r.innerHTML = 'Connecting to session ' +
info.getAttribute('sessionCode');
if (is_msie) {
r.innerHTML += ', please click the button below:<br />';
r.appendChild(doc.createElement('br'));
var b = doc.createElement('input');
b.type = 'button';
b.name = 'join';
b.value = 'Start';
b.onclick = function () {
info.join();
};
r.appendChild(b);
} else {
info.join();
}
},
function (error) {
r.className = 'isl-error';
r.innerHTML = 'Invalid session code!';
/* comment the line above and uncomment the line below if you wish to
* display the error that is sent by the server
*/
//r.innerHTML += error.getDescription();
}
);
return false;
});
I have the following html code :
<form name="uploadForm" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="button" onClick="javascript:submitform();" value="SUBMIT BTN" />
</form>
and here is the javascript function submitform() :
function submitform()
{
var minUpload = 1;
var uploadNo;
var count=document.uploadForm.file_sub.length;
for(a=0;a<count;a++)
{
if(document.uploadForm.file_sub.value != '')
{
uploadNo++;
}
}
if(uploadNo > minUpload){
document.uploadForm.submit();
}else{
alert('Please Upload Atleast ' + minUpload + ' files');
}
}
the javascript is suppose to validate and make sure atleast minUpload of the the file fields a file inside them.
but for some reason when I try to get the length of the file in the function I get an error (according to the debugger of chrome, I get "Uncaught TypeError: Cannot read property 'length' of undefined" ) however I have tried the same thing with checkboxes and it works just fine. What am I doing wrong? is it even possible to do such task in js?
You have to refer to file_sub[]. Fixed function:
var count = document.uploadForm["file_sub[]"].length;
function submitform(){
var minUpload = 1;
var uploadNo;
var files = document.forms['uploadForm']["file_sub[]"];
var count = files.length;
for(var a=0; a<count; a++){
if(files[a].value != ''){
uploadNo++;
}
}
if(uploadNo > minUpload){
document.forms['uploadForm'].submit();
} else {
alert('Please Upload Atleast ' + minUpload + ' files');
}
}
I have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:
function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
default:;
} // switch
} // ff_uploadimages_action
ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.
Here's one way to do it
document.getElementById('upload').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
document.getElementById('filename').value = filename;
}
<input id="upload" type="file" />
<input id="filename" type="text" />
you don't mention jQuery but given it's popularity here's the same solution using jQuery
jQuery:
$('#upload').change(function() {
var filename = $(this).val();
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
$('#filename').val(filename);
});
Demo:
http://jsfiddle.net/pxfunc/WWNnV/4/
HTML:
<input id="upload" type="file" onChange="uploadOnChange(this)" />
<input id="filename" type="text" />
JS:
function uploadOnChange(e) {
var filename = e.value;var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex +1);
}
document.getElementById('filename').value = filename;
}
A shorter way in jQuery would be the following:
HTML
<input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>
jQuery
$("#buttonChooseFile").click(funtion()({
$("#inputFile").click();
});
$("#inputFile").change(function(){
var fileName = $("#inputFile").prop('files')[0]["name"];
$("inputDisplayFileName").val(fileName);
});
In this example the default file upload is hidden so that you can style the 'upload file input' as desired. Clicking the button will trigger the original (hidden) file upload. After choosing the file the .onchange() will do the rest of the work, copying the file the 'read only input text'.