how to set file name to input value - javascript

Below script is working fine .. Its showing file name in alert statement .. But I want filename in input statement. Example if I upload the 1 st file I want file name in id='0' , if it is 2nd one I want file name in id='1'
<body>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input id="0">
<input id="1">
<input id="2">
<input id="3">
<input id="4">
<script>
var inputArray = document.getElementsByClassName('input');
for(var i = 0; i < inputArray.length; i++){
inputArray[i].addEventListener('change',prepareUpload,false);
};
function prepareUpload(event)
{
var files = event.target.files;
var fileName = files[0].name;
document.getElementById("0").value = fileName;
alert(fileName);
}
</script>
</body>
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<input id="mySelect" onchange="myFunction1()" type="file">
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect");
var fileName = files[x].name;
document.getElementById("0").value = fileName;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>

Related

Pass input text to client side and save as variable

I created a script which exports a CSV from Google Sheets. This CSV is exported to a Drive folder, and I initially placed an ID in the code using var folder = DriveApp.getFolderById("ID goes here");
Now, I want to make the export location dynamic for my users. I also want them to select the frequency of automated exports. I created an html file and call a dialog box up for users to input their desired ID and frequency.
function openFolderForm() {
var html = HtmlService.createHtmlOutputFromFile('html')
.setHeight(525)
.setWidth(800);
SpreadsheetApp.getUi().showModalDialog(html, 'Export Settings');
}
In the html file, I have..
<form id="form">
<div class="block form-group">
<input type='text' name='IDdrive' id="IDdrive" style="width: 300px;"/>
</div>
<br>
<p>Frequency?</p>
<div>
<input type="radio" name="radio" id="radioDaily">
<label for="radioDaily">Daily</label>
</div>
<div>
<input type="radio" name="radio" id="radioWeekly">
<label for="radioWeekly">Weekly</label>
</div>
<button type = "submit" class = "action"
onClick="google.script.run.updateSettings();">Submit</button>
</form>
Finally, in my code I have...
function updateSettings(form) {
var formQ1 = form.IDdrive;
if (form.radioDaily == true) { var formQ2 = 1; } else { var formQ2 = 7}
};
function exportCSV() {
var changelogSheetName = "data";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var tab = ss.getSheetByName('data');
var folder = DriveApp.getFolderById(formQ1); //putting in dynamic form
etc etc etc
function createTimeTrigger() {
ScriptApp.newTrigger("exportCSV")
.timeBased()
.atHour(3)
.inTimezone("America/Los_Angeles")
.everyDays(formQ2) //input radio variable answer here
.create();
}
};
However, my code is not working. The variables for the form answers are not passing to client side successfully. The code does work if I put in the ID directly.
I realize that this has been asked in various forms already on this site, but I have read most of those threads and have still been unable to resolve. Could someone help out of Scripts App newbie please? :)
Full code below, starting with .gs :
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ui = SpreadsheetApp.getUi();
ui.createMenu('Scripts')
.addItem('Export CSV', 'exportCSV')
.addItem('Update export settings', 'openFolderForm')
.addToUi();
}
function openFolderForm() {
var html = HtmlService.createHtmlOutputFromFile('html').setHeight(525).setWidth(800);
SpreadsheetApp.getUi().showModalDialog(html, 'Export Settings');
}
function updateSettings(form) {
var formQ1 = form.IDdrive;
if (form.radioDaily == true) { var formQ2 = 1; } else { var formQ2 = 7};
google.script.host.close();
};
function exportCSV() {
var changelogSheetName = "data";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var tab = ss.getSheetByName('data');
var folder = DriveApp.getFolderById(formQ1);
//export code here
}
function convertRangeToCsvFile_(csvFileName, sheet) {
var activeRange = sheet.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
function createTrigger() {
ScriptApp.newTrigger('exportCSV')
.timeBased()
.atHour(3)
.everyDays(formQ2) //radio question here
.inTimezone("America/Los_Angeles")
.create();
and HTML full...
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<title><b>Output Folder</b></title>
</head>
<body>
<p>Enter the ID of your output folder. A Drive ID is made up by the characters after the last /folder/ in the URL</p>
<form id="form">
<div class="block form-group">
<input type='text' name='IDdrive' id="IDdrive" style="width: 300px;"/>
</div>
<div>
<input type="radio" name="radio" id="radioDaily"> <label for="radioDaily">Daily</label>
</div>
<div>
<input type="radio" name="radio" id="radioWeekly"> <label for="radioWeekly">Weekly</label>
</div>
<br>
<div class="inline form-group">
<input type="button" value="Submit" class="action" onClick="google.script.run.updateSettings();" /> //or "google.script.run.updateSettings(this.parentNode);"
<input type="button" value="Cancel" class="cancel" onClick="google.script.host.close();" />
</div>
<br>
</form>
</body>
</html>
Your not passing anything to updateSettings google.script.run.updateSettings();>
I would do it like this:
<input type = "button" value="Submit" onClick="google.script.run.updateSettings(this.parentNode);" />
I'm running this as a dialog and it runs okay now. I added values to the radio buttons and now the weekly one returns 'weekly' and the daily one returns 'daily' and the IDdrive returns a string.
gs:
function openFolderForm() { SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1').setHeight(525).setWidth(800), 'Export Settings');
}
function updateSettings(form) {
console.log(form)
var formQ1=form.IDdrive;
if (form.radioDaily == true) { var formQ2 = 1; } else { var formQ2 = 7}
}
function exportCSV() {
var changelogSheetName = "data";
var ss=SpreadsheetApp.getActive();
var sheets=ss.getSheets();
var tab=ss.getSheetByName('data');
var folder=DriveApp.getFolderById(formQ1);
}
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<title><b>Output Folder</b></title>
</head>
<body>
<p>Enter the ID of your output folder. A Drive ID is made up by the characters after the last /folder/ in the URL</p>
<form>
<input type='text' name='IDdrive' id="IDdrive" style="width: 300px;"/><br />
<input type="radio" name="radio" id="radioDaily" value="daily"> <label for="radioDaily">Daily</label><br />
<input type="radio" name="radio" id="radioWeekly" value="weekly"> <label for="radioWeekly">Weekly</label><br />
<input type="button" value="Submit" class="action" onClick="google.script.run.updateSettings(this.parentNode);" />
<input type="button" value="Cancel" class="cancel" onClick="google.script.host.close();" />
</form>
</body>
</html>
Got it to work. The secret was needed to just JSON to properly store the form input criteria.
CODE
function updateSettings(formObject) {
var uiForm = SpreadsheetApp.getUi();
JSON.stringify(formObject);
var formText = formObject.formQ1;
var formRadio = formObject.formQ2;
if (formRadio == "Daily") { var frequency = 1; } else { var frequency = 7};
etc etc
HTML
<form id="myForm" onsubmit="event.preventDefault(); google.script.run.updateSettings(this); google.script.host.close();">
<div>
<input type='text' name='formQ1' id="formQ1" style="width: 300px;"/>
</div>
<div class="inline form-group">
<input type="radio" name="formQ2" id="formQ2" value="Daily" /> <label for="radioDaily">Daily</label>
</div>
<div>
<input type="radio" name="formQ2" id="formQ2" value="Weekly" /> <label for="radioWeekly">Weekly</label>
</div>
<br><br>
<div class="inline form-group">
<input type="submit" value="Submit" style="color:#4285F4"/>
<input type="button" value="Cancel" class="cancel" onClick="google.script.host.close();" />

Multi File upload "files[]" javascript validation

On my site I have multi file upload form with fields:
<input name="files[]" type="file" id="files" size="30" />
<input name="files[]" type="file" id="files" size="30" />
<input name="files[]" type="file" id="files" size="30" />
and I want to validate this fields with javascript code, I know how to get value for some simple fields with javascript but I don`t know how to get values from this fields with names "files[]", how javascript see this fields, array or...?
How to apply validation of size and file type using javascript
<!DOCTYPE html>
<html>
<body>
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<button onclick="myFunction()">Get File Name-Type-Size</button>
<script>
function myFunction() {
var input, file;
if (!window.FileReader) {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
var input=document.getElementsByName('files[]');
for(var i=0;i<input.length;i++){
var file = input[i].files[0];
bodyAppend("p", "File " + file.name + " is " + formatBytes(file.size) + " in size"+" & type is "+ fileType(file.name));
}
}
//function to append result to view
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
//function to find size of file in diff UNIT
function formatBytes(bytes,decimals) {
if(bytes == 0) return '0 Byte';
var k = 1000;
var dm = decimals + 1 || 3;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
//function to find file type
function fileType(filename){
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}
</script>
</body>
</html>
Check this now you can put conditions on type of file & size.
// Try this jQuery ;)
$("form").on('change', 'input[type=file]', function() {
var file;
var this = $(this);
if (file = this.files[0])
{
var img = new Image();
img.onload = function () {
// correct
// check alert(img.src)
}
img.onerror = function () {
//error info
};
img.src = _URL.createObjectURL(file);
}
}
<!DOCTYPE html>
<html>
<body>
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<button onclick="myFunction()">Get File Type</button>
<script>
function myFunction() {
var file=document.getElementsByName('files[]');
for(var i=0;i<file.length;i++){
console.log(file[i].value);
}
}
</script>
</body>
</html>
you can get files name like this.
Thanks Bhavik vora But already done with this one
<html>
<head>
<title>client-side image (type/size) upload validation</title>
<meta charset=utf-8>
<style>
</style>
</head>
<body>
<form><fieldset><legend>Image upload</legend>
<input type="file" name="file[]" onchange="getImg(this,100,'jpeg|png')">
<input type="file" name="file[]" onchange="getImg(this,100,'jpeg|png')">
</fieldset>
</form>
<script>
function getImg(input,max,accepted){
var upImg=new Image(),test,size,msg=input.form;
msg=msg.elements[0].children[0];
return input.files?validate():
(upImg.src=input.value,upImg.onerror=upImg.onload=validate);
"author: b.b. Troy III p.a.e";
function validate(){
test=(input.files?input.files[0]:upImg);
size=(test.size||test.fileSize)/1024;
mime=(test.type||test.mimeType);
mime.match(RegExp(accepted,'i'))?
size>max?(input.form.reset(),msg.innerHTML=max+"KB Exceeded!"):
msg.innerHTML="Upload ready...":
(input.form.reset(),msg.innerHTML=accepted+" file type(s) only!")
}
}
</script>
</body>
</html>

there are two html pages. I want the data status of first pages to saved when I reverting from next page to first page

When I click on back button of next page the check box value should not be reset.
It should be same as I checked or unchecked. The code from the first and next page is below.
First Page
<!DOCTYPE html>
<html>
<body>
<form>
<input type="checkbox" name="code" value="ECE">ECE<br>
<input type="checkbox" name="code" value="CSE">CSE<br>
<input type="checkbox" name="code" value="ISE">ISE<br>
<br>
<input type="button" onclick="dropFunction()" value="save">
<br><br>
<script>
function dropFunction() {
var branch = document.getElementsByName("code");
var out = "";
for (var i = 0; i < branch.length; i++) {
if (branch[i].checked == true) {
out = out + branch[i].value + " ";
window.location.href="next.html";
}
}
}
</script>
</form>
</body>
</html>
Next Page
<html>
<head>
<title>Welcome to </title>
</head>
<body color="yellow" text="blue">
<h1>welcome to page</h1>
<h2>here we go </h2>
<p> hello everybody<br></p>
</body>
<image src="D:\images.jpg" width="300" height="200"><br>
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.location.href="first.html";
}
</script>
</body>
</html>
Full solution: example. First add ids to your checkboxes:
<input type="checkbox" name="code" value="ECE" id='1'>ECE<br>
<input type="checkbox" name="code" value="CSE" id='2'>CSE<br>
<input type="checkbox" name="code" value="ISE" id='3'>ISE<br>
<input id="spy" style="visibility:hidden"/>
Then change your dropFunction:
function dropFunction() {
var branch = document.getElementsByName("code");
var out = "";
localStorage.clear();
for (var i = 0; i < branch.length; i++)
if (branch[i].checked == true)
localStorage.setItem(branch[i].id, true);
for (var i = 0; i < branch.length; i++) {
if (branch[i].checked == true) {
out = out + branch[i].value + " ";
window.location.href="next.html";
}
}
}
And add some new javascript code to first.html:
window.onload = function() {
var spy = document.getElementById("spy");
if(spy.value=='visited')
for(var i=1;i<=3;i++)
if(localStorage.getItem(i))
document.getElementById(i).checked=true;
spy.value = 'visited';
}

multiple forms with javascript

I am trying to show forms according to user input in the text box but it is showing it one time only...please help...
index.html:
<html>
<head>
<script type="text/javascript" src="demo1.js"></script>
</head>
<body>
<form name="su">
<input type="text" name="tt" onkeyup="javascript:toggleFormVisibility();" id="sub"/> </a>
</form>
<form id="subscribe_frm" style="display:none">
NAME:<input type="text" name="text">
EMAIL:<input type="text" name="text">
PASSWORD:<input type="text" name="text">
</form>
demo.js:
function toggleFormVisibility()
{
var txt = document.getElementById('sub').value;
for(var i=0;i<txt;i++)
{
var frm_element = document.getElementById('subscribe_frm');
var vis = frm_element.style;
vis.display = 'block';
}
}
A bit of a guess, but I think you are trying to create multiple copies of your form. Try this out:
http://jsfiddle.net/QnrM9/
JS
function toggleFormVisibility() {
var txt = document.getElementById('sub').value;
var neededChildren = txt.length - document.getElementById('form_container').children.length + 1;
for (var i = 0; i < neededChildren; i++) {
var frm_element = document.getElementById('subscribe_frm').cloneNode(true);
var vis = frm_element.style;
vis['display'] = 'block';
document.getElementById("form_container").appendChild(frm_element);
}
}
document.getElementById('sub').addEventListener('keyup', toggleFormVisibility);
HTML
<form name="su">
<input type="text" name="tt" id="sub" />
</form>
<div id="form_container">
<form id="subscribe_frm" style="display:none">NAME:
<input type="text" name="text" />EMAIL:
<input type="text" name="text" />PASSWORD:
<input type="text" name="text" />
</form>
</div>

Create a link based on values from a Html form and redirect them to it

What I'm trying to do is to redirect people to a link depending of what they have summited on the form (the link is built using the values from the form fields)
This is the Form:
<form id="form">
<div class="formbox">
<div class="radio-toolbar">
<input type="radio" id="iconapp1" name="department" value="1250"/>
<label for="iconapp1">PP</label><br>
<input type="radio" id="iconapp2" name="department" value="944"/>
<label for="iconapp2">EP</label><br>
</div>
<div class="radio-bar1">
<input type="radio" id="enginemake1" name="enginemake" value="6"/>
<label for="enginemake1"> Chevrolet</label><br>
<input type="radio" id="enginemake2" name="enginemake" value="8"/>
<label for="enginemake2"> Chrysler</label><br>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar3">
<select name="powerrange">
<option id="powerrange1" value="28">100</option>
<option id="powerrange2" value="128">200</option>
<option id="powerrange3" value="228" selected>300</option>
</select>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar4">
<input type="radio" id="location1" name="location" value="store"/>
<label for="location1"> America (NT - ST)</label><br>
<input type="radio" id="location2" name="location" value="store.au"/>
<label for="location2"> Australia and Oceania</label><br>
</div>
<div class="radio-bar2">
<input onclick="goToPage();" type="button" class="buttonmyapp" value="Submit" />
</div>
</div>
</form>
The link I'm trying to build using the values selected will look like this:
http://{location}.mydomain.com/product-catalog.aspx?section=-{department}-{enginemake}-{powerrange}-
Each bracketed section needs to be replaced by the value of the select with the corresponding name.
First include the jquery library link or download js and link
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function goToPage(){
var location = $('input[name=location]:checked').val();
var department = $('input[name=department]:checked').val();
var enginemake = $('input[name=enginemake]:checked').val();
var powerrange = $('select[name=powerrange]').val();
window.location.href = "http://"+location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
}
</script>
After the goToPage function on the submit button validates the response change the src attribute of the form should work fine.
So in jQuery it should look something like
var location = $('input[name=location]:checked', '.radio-bar4').val();
var dept = $('input[name=location]:checked', '.radio-bar4').val();
var engine = $('input[name=enginemake]:checked', '.radio-bar1').val();
var power = $('powerrange').val() ;
var domain = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+dept+"-"+engine+"-"+power+"-";
$("#form").attr("action", domain);
you can try this
HTML
<select id="powerrange" name="powerrange">
JAVASCRIPT
function goToPage()
{
var location;
var department;
var enginemake;
var powerrange;
pName = document.getElementById('powerrange');
powerrange = pName.options[pName.selectedIndex].value;
var form = document.getElementById('form');
var ele = form.getElementsByTagName('input');
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute('type')=='checkbox')
{
if(ele[i].getAttribute('name')=='department')
{
if(ele[i].checked)
department = ele[i].value;
}
else if(ele[i].getAttribute('name')=='enginemake')
{
if(ele[i].checked)
enginemake = ele[i].value;
}
else if(ele[i].getAttribute('name')=='location')
{
if(ele[i].checked)
location = ele[i].value;
}
else;
}
}
var url = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
form.setAttribute('action',url);
form.submit();
}

Categories