Display Data in New Tab in Same Browser[Working Code] - javascript

I have a Google Script that Displays List of Data from Google Drive and this is what it looks like.
This code is working so perfect you just need index.html and code.gs and here is the code for both of them. (So for those who are using google app script in your site this will help.)
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage()
{
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ "</br><B>Last modified: </B>"+item[2]+ "</br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td
{
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text">Search File : <input type="text" id="idSrchTerm" name="search" class = "my_text">
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();"/>
</div>
<div id = "count" class = "my_text"></div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
function doGet(e) { // main function
var template = HtmlService.createTemplateFromFile('index.html');
return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'";
var names = [];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize;
names.push(name);
Logger.log(file.getUrl());
}
return names;
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn;
}
}
My only target here is how can I display the result in New Window? I mean I will type any string in textbox and click the button then thats it! the output will display in a new window like for example output.html
TYSM for future help.

Related

How to get info from google sheets based on drop list selection?

In my webapp show a drop list that get the sheets name from a google sheets file so I'm trying to get the sheet info based on the selected sheet from the drop list .
the code works but not based on the selection of droplist.
what I did wrong ?
here is the full sample hopefully it will help to identify the issue
CODE.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('dup');
}
function getSheetNames() {
var ss=SpreadsheetApp.getActive();
var shts=ss.getSheets();
var sObj={sA:[]};
shts.forEach(function(sh){
sObj.sA.push(sh.getName());
})
return sObj;
}
function getDataFromServer(e) {
var ss=SpreadsheetApp.getActive();
var data =ss.getSheetByName(e.name).getRange("B2:J22").getValues();
var ar = data.splice(0,1); //add headers
data.forEach(function(f) {
if (~f.indexOf(e.searchtext)) ar.push(f);
});
e['sA']=getSheetNames().sA;
return ar;
}
dup.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select id="sel1"></select><label for="sel1">Report Date </label>
</body>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(sObj){
var select=document.getElementById('sel1');
sObj.sA.unshift('Please Select a report date');
select.options.length=0;
for(var i=0;i<sObj.sA.length;i++) {
select.options[i]=new Option(sObj.sA[i],sObj.sA[i]);
}
})
.getSheetNames();
});
const loaded = new Promise((res, rej) => {
google.charts.load('current');
google.charts.setOnLoadCallback(res);
});
let wrapper = null;
async function drawTable(arr) {
await loaded; //wait if charts is not loaded
wrapper = new google.visualization.ChartWrapper({
chartType: 'Table',
dataTable: arr,
containerId: 'table_div',
});
wrapper.draw();
}
function getData(f) {
google.script.run
.withSuccessHandler(drawTable,function(rObj){
$('#sel1').css('background-color','#ffffff');
var select=document.getElementById('sel1');
rObj.sA.unshift('Please Select by Report Date');
select.options.length=0;
for(var i=0;i<rObj.sA.length;i++) {
select.options[i]=new Option(rObj.sA[i],rObj.sA[i]);
}
})
.getDataFromServer(f);
}
</script>
<body>
<form>
<input type="button"id="display"class="btn btn-primary" value="retrieve report Data" onClick="getData(this.parentNode)" />
</form>
<div id="table_div"></div>
</body>
</html>
Here's your html a little better organized. I haven't checked all of the functions but atleast the select tag is inside your form and there's just a simple html structure.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(sObj){
var select=document.getElementById('sel1');
sObj.sA.unshift('Please Select a report date');
select.options.length=0;
for(var i=0;i<sObj.sA.length;i++) {
select.options[i]=new Option(sObj.sA[i],sObj.sA[i]);
}
})
.getSheetNames();
});
const loaded = new Promise((res, rej) => {
google.charts.load('current');
google.charts.setOnLoadCallback(res);
});
let wrapper = null;
async function drawTable(arr) {
await loaded; //wait if charts is not loaded
wrapper = new google.visualization.ChartWrapper({
chartType: 'Table',
dataTable: arr,
containerId: 'table_div',
});
wrapper.draw();
}
function getData(f) {
google.script.run
.withSuccessHandler(drawTable,function(rObj){
$('#sel1').css('background-color','#ffffff');
var select=document.getElementById('sel1');
rObj.sA.unshift('Please Select by Report Date');
select.options.length=0;
for(var i=0;i<rObj.sA.length;i++) {
select.options[i]=new Option(rObj.sA[i],rObj.sA[i]);
}
})
.getDataFromServer(f);
}
</script>
</head>
<body>
<form>
<select id="sel1"></select><label for="sel1">Report Date </label>
<input type="button"id="display"class="btn btn-primary" value="retrieve report Data" onClick="getData(this.parentNode)" />
</form>
</body>
</html>
This is how I've done it. This script starts off by getting a list of all spreadsheets in your account and it populates a drop down on the webapp. You then select the spreadsheet and it goes back to the server to get all of the sheets for the selected spreadsheet. Once you make your selection it then loads that entire sheet on the web app and provides the capability for you to edit the data on that sheet.
Code.gs:
function htmlSpreadsheet(ssO) {
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(ssO.id);
var sht=ss.getSheetByName(ssO.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
s+='</body></html>';
var namehl=Utilities.formatString('<h1>%s</h1>', ss.getName());
var shnamehl=Utilities.formatString('<h2>%s</h2>', sht.getName());
var opO={hl:s,name:namehl,shname:shnamehl};
return opO;
}
function updateSpreadsheet(updObj) {
var i=updObj.rowIndex;
var j=updObj.colIndex;
var value=updObj.value;
var ss=SpreadsheetApp.openById(updObj.id);
var sht=ss.getSheetByName(updObj.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet() {
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getAllSpreadSheets() {
var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
var s = '';
var vA=[['Select Spreadsheet',0]];
while(files.hasNext())
{
var file = files.next();
var fileName=file.getName();
var fileId=file.getId();
vA.push([fileName,fileId]);
}
//return vA;
return {array:vA,type:'sel1'};
}
//working on this function right now 2017/11/08
function getAllSheets(ssO) {
var ss=SpreadsheetApp.openById(ssO.id);
var allSheets=ss.getSheets();
var vA=[['Select Sheet']];
for(var i=0;i<allSheets.length;i++)
{
var name=allSheets[i].getName();
vA.push([name]);
}
return {array:vA,type:'sel2'};
}
htmlss.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#msg').html('Please wait. Collecting a list of all Spreadsheets...');
google.script.run
.withSuccessHandler(updateSelect)
.getAllSpreadSheets();
});
function updateSS(i,j)
{
var str='#txt' + String(i) + String(j);
var value=$(str).val();
var ssId=$('#sel1').val();
var name=$('#sel2').val();
var updObj={rowIndex:i,colIndex:j,value:value,id:ssId,name:name};
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(updateSheet)
.updateSpreadsheet(updObj);
}
function updateSheet(data)
{
//$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
function updateSelect(dtO)
{
$('#sel1').css('background','#ffffff');
$('#sel2').css('background','#ffffff');
$('#msg').html('Spreadsheet List has been updated. Now select a SpreadSheet to display');
var select = document.getElementById(dtO.type);
var vA=dtO.array;
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i][0],vA[i][vA[i].length-1]);
}
}
function loadSelectSheet()
{
var shId=$('#sel1').val();
var name=$('#sel1').text();
$('#sel1').css('background','#ffff00');
document.getElementById('ssname').innerHTML="";
var ssO={name:name ,id:shId}
google.script.run
.withSuccessHandler(updateSelect)
.getAllSheets(ssO);
}
function displaySelectedSheet()
{
var ssId=$('#sel1').val();
var name=$('#sel2').val();
$('#sel2').css('background','#ffff00');
document.getElementById('shname').innerHTML="";
var ssO={id:ssId,name:name};
google.script.run
.withSuccessHandler(displaySheet)
.htmlSpreadsheet(ssO);
}
function displaySheet(opO)
{
$('#sel2').css('background','#ffffff');
document.getElementById('ssname').innerHTML=opO.name;
document.getElementById('shname').innerHTML=opO.shname;
document.getElementById('sss').innerHTML=opO.hl;
}
console.log('My Code');
</script>
<style>
th{text-align:left}
</style>
</head>
<body>
<div id="msg"></div><br />
<br /><select id="sel1" onChange="loadSelectSheet();"></select>
<br /><select id="sel2" onChange="displaySelectedSheet();"></select>
<div id="ssname"></div>
<div id="shname"></div>
<div id="sss"></div>
</body>
</html>
I did this several years ago but I still use it occasionally.

ERROR: Can't find variable SSL

I'm trying to pick a value from JSON and insert it on a diferents text boxes but it show the value "undefined". The objective is insert link on name space and link space and save it on LocalStorage and some statick values like google and yahoo. Please can someone help me? Thanks you so much.
EDIT: Now is solved, and now dont work the buttons, some one? Please
NEW PROBLEM:The error only appear if I press the buttons (it don't create the buttons).
ERROR: Can't find variable SSL
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = ss =function() {
var data= '';
if (MyJSON.length > 0) {
for (i = 0; i < MyJSON.length; i++) {
data += '<tr>';
data += '<td>' + MyJSON[i].name+ '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(MyJSON.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
MyJSON.name.push(url.trim());
el.value = '';
this.FetchAll();
}
if (url) {
MyJSON.url.push(url1.trim());
el1.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = MyJSON.name[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.urls.splice(item, 1, url.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
MyJSON.name.splice(item, 1);
this.FetchAll();
};
}
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
}

Prevent Blank Page and Display Data in Table

I have a working code in Google Script that is compost on Index.HTML and code.gs actually this code is working if you will test it in your google app script and here it is
Index.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length; // total elements of results
var table = document.getElementById('output');
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
}
document.writeln("End of results...");
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
Search: <input type="text" id="idSrchTerm" name="search">
<input type="button" value="Search" name="submitButton" onclick="displayMessage()"/>
</div>
<table id ="output">
<tr>
<th>File Details</th>
</tr>
<tr>
<td>
<script>
function handleResults(results){
var length=results.length; // total elements of results
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|"); // split the line |~|, position 0 has the filename and 1 the file URL
document.writeln("<b><a href='"+item[1]+"' target='_blank'>"+item[0]+"</b></a> (Last modified: "+item[2]+")<br/><br/>"); // write result
}
document.writeln("End of results...");
}
</script>
</td>
</tr>
</table>
</body>
</html>
and this is Code.GS
function doGet(e) { // main function
var template = HtmlService.createTemplateFromFile('index.html');
return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'";
var names = [];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();
var lm = file.getLastUpdated();
var owner = file.getOwner().getName();
var filesize = file.getSize();
var name = file.getName() +"|~|"+file.getUrl()+"|~|"+lm+"|~|"+owner+"|~|"+filesize;
names.push(name);
Logger.log(file.getUrl());
}
return names;
}
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn;
}
This code is working perfectly but the output of this is everytime i searched a data it transfers me to a new page with the search result.
My Question is How can I display the data in my Table Tag?
Here is the image of where should be the data will put.
Image Link

How to Pass Textbox Value from One Page to another?

I have 3 Files.
index.html
code.gs and
display.html
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text"><input type="text" id="idSrchTerm" name="search" class = "my_text" >
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" />
<?var url = getScriptUrl();?><a target="_blank" href='<?=url?>?page=display'><input type="button" value="Open In New Tab" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" value='display.html'/></a>
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
var scriptProperties = PropertiesService.getScriptProperties();
function doGet(e) {
Logger.log( Utilities.jsonStringify(e) );
if (!e.parameter.page) {
return HtmlService.createTemplateFromFile('index').evaluate();
}
return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
return HtmlService.createHtmlOutputFromFile('display');
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'"; //single quotes are needed around searchterm
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('SQuery', searchTerm);
var userProperties = PropertiesService.getUserProperties();
var SQuery = userProperties.getProperty('SQuery');
Logger.log(SQuery);
var names = [];
var files = DriveApp.searchFiles(searchFor);
var searchQ = searchTerm;
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize+"|~|"+searchQ; // Im concatenating the filename with file id separated by |~|
names.push(name); // adding to the array
Logger.log(file.getUrl());
}
return names; // return results
}
// Process the form
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn; // return the results
}
display.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body onload ="clearBox(); displayMessage();">
<div class="container">
<p class = "my_text">
<input type="text" id="idSrchTerm" name="search" class = "my_text" value = "outing" >
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
actually the output of index.html and output.html are the same they have textbox and the other one has a button. This code is working my only proble here is how can I pass textbox value from index.html to textbox value of display.html
This is what index.html looks like
and this is what display.html looks like
my only target here is to pass textbox value from one site to another and from that I can run my code <body onload> Thats all i need pass textbox value from another textbox from other site TYSM for help
Ty local storage
save the variable
localStorage.setItem('NameOfLocalStorage',Value);
Get the value
localStorage.getItem('NameOfLocalStorage');
You can send data via link, example:
window.location.href = "output.html?" + encodeURIComponent('blah blah bla')
and you can retrive data in output.html
var data = decodeURIComponent(window.location.search.substr(1))

how to display image in file upload dynamically

I have created a function for file upload. I get the file name and file type and don't know how to display image using dynamic control!
function AddFileUpload() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
'" type="file"/>' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div) {
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
Here's some code from a for-fun project I have.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('mFileInput').addEventListener('change', onFileChosen, false);
}
// fileVar is an object as returned by <input type='file'>
// imgElem is an <img> element - can be on/off screen (doesn't need to be added to the DOM)
function loadImgFromFile(fileVar, imgElem)
{
var fileReader = new FileReader();
fileReader.onload = onFileLoaded;
fileReader.readAsBinaryString(fileVar);
function onFileLoaded(fileLoadedEvent)
{
var result,data;
data = fileLoadedEvent.target.result;
result = "data:";
result += fileVar.type;
result += ";base64,";
result += btoa(data);
imgElem.src = result;
imgElem.origType = fileVar.type; // unnecessary for loading the image, used by a current project.
}
}
function onFileChosen(evt)
{
if (this.files.length != 0)
{
var tgtImg = byId('tgt');
var curFile = this.files[0];
loadImgFromFile(curFile, tgtImg);
}
}
</script>
<style>
</style>
</head>
<body>
<input id='mFileInput' type='file'/><br>
<img id='tgt' />
</body>
</html>

Categories