I have a spreadsheet at work that contains information on various different devices we use.
The spreadsheet contains information like the Original Equipment Manufacturer, Storage capacity, format, Etc. There are a total of 10 Columns, and up to 359 rows currently; but the spreadsheet will expand from general use.
I have created a sidebar application in google sheets using Aps script and HTML, in order to make requesting support for these objects simpler. I am running in to an issue with capturing the data typed into an input field. Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class = "Container"><!-- Begin CONTAINER div -->
<div class="row"><!-- Begin ROW div -->
<div class="col s24 "><!-- Beginning of Header div -->
<h5 class="col s24"offset-s3> Edit a Kit </h5>
<div><!-- Text input field for Kit search -->
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Enter Kit Name</label>
</div>
</div><!-- end of Text Input for Kit search -->
<!-- Start of Submit btn div -->
<div class="input-field col s12">
<button class="btn waves-effect waves-light" id="search" onclick ="submitData()">Search
<i class="material-icons right">search</i>
</button>
</div><!-- End of Submit btn div -->
<div class="divider"></div>
<div><!-- beginning of kit contents div -->
<!-- Users need to enter kit names into a text input field, similar to the create kit page -->
<h5 id = "kit" class = "section"></h5>
</div><!-- end of kit contents div -->
<div class="divider"></div>
<!-- Start of the HOME PAGE button Div -->
<div class="input-field col s12">
<button class="btn waves-effect waves-light" onclick="google.script.run.withSuccessHandler(changePage).newPage('Card Request Form')">Home
<i class="material-icons right">home</i>
</button>
</div><!-- end of the HOME PAGE button div -->
</div><!-- End of Header div --->
</div><!-- End of ROW Div -->
</div><!-- End of CONTAINER Div -->
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
function changePage(page) {
document.write(page);
}
// function alertA() {
// alert("Your code Failed to Run");
// };
function alertB() {
alert("Success! Click 'OK' to see your results");
};
function submitData() {
var data = document.getElementById('search').value;
var outPut = document.getElementById('kit');
var display = outPut.innerHtml = "THIS IS WORKING AS EXPECTED";
// alert(display);
};
function outputCard(submitData) {
};
</script>
</body>
</html>
I am trying to access the input data from the "Submit btn div" using the function "submitData()", but have been unsuccessful in doing so. In the version i've uploaded, I am simply trying to capture that information, and print it back out to the "kit contents div" but have been unsuccessful.
For clarity, I am doing this in a Google Apps scripts, as a sidebar extension to a google sheets spreadsheet. The goal is to take that input, and parse over the information for all of the informaton referenced in the first Full paragraph; and then return any items relevantr to the users search terms in the "kit contents div". I am not able to capture the input in Google Apps script though. Here is a copy of my gs code:
//This function searches for cards by the value typed into the text input field
function cardSearch(data) {
var app = SpreadsheetApp;
var log = app.openById("My Spreadsheet's ID");
var kitContents = app.openById("My Spreadsheet's ID");
var cards = log.getRange("A3:J").getValues();
var kitType = kitContents.getRange("A3:J359").getValues();
for (i=0; i<kitType[data]; i++){
return kitType[data];
}
Logger.log(kitType[356])
// for some reason, the array literal ends at index #356, where as the spreadsheet is up to 359 rows, but stops at ID#354
};
function alert(data) {
return "received input " +data.display;
};
//This function loads the webpage content of the HTML file "Card Request Form" as a sidebar in the main spreadsheet
function showRequestForm() {
var form = HtmlService.createTemplateFromFile("Card Request Form");
var html = form.evaluate();
SpreadsheetApp.getUi().showSidebar(html);
};
//This function allows us to navigate pages that exists in the document
function newPage(page) {
return HtmlService.createHtmlOutputFromFile(page).getContent()
};
I need help understanding how to cpature the input, and pass it back to the GS (I believe it's the same as passing it to the server) in order to run the cardSearch Function with that capturted data.
Here's an example form that I've used to collect receipt information. You can display it as a sidebar, a dialog or run it as a webapp. It has a numerical input, a text input and a textarea. It also allows you to upload a file.
thehtml.hmtl:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
<style>
input,textarea{margin:5px 5px 5px 0;}
</style>
</head>
<body>
<h3 id="main-heading">Receipt Information</h3>
<div id="formDiv">
<form id="myForm">
<br /><input type="date" name="date" id="dt"/>
<br /><input type="number" name="amount" placeholder="Amount" id="amt" />
<br /><input type="text" name="vendor" placeholder="Vendor" id="vndr"/>
<br /><textarea name="notes" cols="40" rows="2" placeholder="NOTES"></textarea>
<br/>Receipt Image
<br /><input type="file" name="receipt" id="img" />
<br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
</form>
</div>
<div id="status" style="display: none">
<!-- div will be filled with innerHTML after form submission. -->
Uploading. Please wait...
</div>
</body>
</html>
Codge.gs:
function onOpen() {
SpreadsheetApp.getUi().createMenu('Receipt Collection')
.addItem('Run as Dialog', 'showAsDialog')
.addItem('Run as Sidebar', 'showAsSidebar')
.addToUi();
var sh=SpreadsheetApp.getActive().getSheetByName("Sheet1");
sh.getRange(sh.getLastRow()+1,1).activate();
}
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Sheet1').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function doGet() {
var output=HtmlService.createHtmlOutputFromFile('receipts').setTitle('thehtml');
return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).addMetaTag('viewport', 'width=360, initial-scale=1');
}
function showAsDialog() {
var ui=HtmlService.createHtmlOutputFromFile('thehtml');
SpreadsheetApp.getUi().showModelessDialog(ui, 'Receipts')
}
function showAsSidebar() {
var ui=HtmlService.createHtmlOutputFromFile('thehtml');
SpreadsheetApp.getUi().showSidebar(ui);
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd")
return {date:datestring};
}
globals.gs:
var receiptImageFolderId='upload file folder id';
var SSID='spreadsheet id';
Related
In my Google Application Script web I am loading dynamically Google Doc as HTML. If I insert second HTML exactly the same way then it crashes the layout.
You can test it here
Test scenario 1
Load page
wait till see the text (file 1 is loaded)
go to the other tab and load file2
go back to the first tab and the layout is different (the error is not consistent in terms when and how it performs)
Test scenario 2
Load page
wait till see the text (file 1 is loaded)
load file 3
check the bottom of the page. New test appears and everything is ok
Test scenario 3
Load page
wait till see the text (file 1 is loaded)
load file 3
check the bottom of the page. New test appears and everything is ok
go to the other tab and load file2
go back to the first tab and the layout is different (the error is not consistent in terms when and how it performs)
Server side code looks like. NOTE that from file3 are removed <head> tags.
Could someone explain and hopefully suggest a solution to this issue?
function doGet() {
return HtmlService.createHtmlOutputFromFile("index");
}
function getGoogleDocumentAsHTML(file){
console.log(file)
if (file == 1){
var docID ="1vRMY6bIkUc_J6qDOUJszIYAtIWH-aHTdYYgCmlL4"
}
if (file == 2 || file == 3){
var docID ="1VBpazC3SO2hx4PA7r3A2jud5O9-teNu0nvvnIDac"
}
var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+docID+"&exportFormat=html&format=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url,param).getContentText()
// return cleanHTML(html)
if (file == 3 ){
return cleanHTML(html)
}
return html
//return HtmlService.createHtmlOutput(html).getContent()
}
function cleanHTML(html){
// nuke the whole head section, including the stylesheet and meta tag
html = html.replace(/<head>.*<\/head>/, '');
// remove almost all html attributes
// html = html.replace(/ (id|style|start|colspan|rowspan)="[^"]*"/g, '');
// html = html.replace(/ (id|class|style|start|colspan|rowspan)="[^"]*"/g, '');
// remove all of the spans, as well as the outer html and body
// html = html.replace(/<(span|\/span|body|\/body|html|\/html)>/g, '');
// clearly the superior way of denoting line breaks
// html = html.replace(/<br>/g, '<br />');
return html
}
and html part is here
<!DOCTYPE html>
<html>
<head>
<base target="_self">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" media="screen,projection" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.9.3/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.9.3/js/tabulator.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.9.3/css/materialize/tabulator_materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
</head>
<body>
<div class="row">
<div class="col s12">
<ul class="tabs" id="tabsTest">
<li class="tab col s3">HTML from file - loaded</li>
<li class="tab col s3">Second to be loaded</li>
</ul>
</div>
<div id="test1" class="col s12">
<button id ="testingAdmin" class="waves-effect btn" onClick="getHTML(2)">Load second HTML</button>
<div id="test" class="container col s12"> </div>
</div>
<div id="test2" class="col s12">
<button id ="testingAdmin" class="waves-effect btn" onClick="getHTML(3)">Load third HTML</button>
<div id="testovani" class="container col s12"></div>
<div id="test3" class="container col s12"> </div>
</div>
<script>
function getHTML(file){
google.script.run.withSuccessHandler(
function(output){
if (file == 1){
document.getElementById("testovani").innerHTML = output
}
if (file == 2){
document.getElementById("test").innerHTML = output
}
if (file == 3){
document.getElementById("test3").innerHTML = output
}
}
).getGoogleDocumentAsHTML(file);
}
document.addEventListener("DOMContentLoaded", function(event) {
var options ={}
var tabs = document.querySelectorAll('.tabs')
var tabsOptions = {
onShow : function(e) {
console.log(e.id)
switch (e.id){
case "test2":
console.log("testing")
break;
default:
}
}
}
var instance = M.Tabs.init(tabs, options);
getHTML(1)
});
</script>
</body>
</html>
I'm working on a project, where the user will use side-bar html page, as a form to update a sheet (very basic operation).
I'm having issue with the autocomplete part.
I'm a beginner to code html with google apps script, so please let me know if you don't have enough information.
The script is supposed to get names from a google sheets, and populate it to the autocomplete item.
I followed a tutorial doing practically the same operation, but based on a web app using a google spreadsheet ==> this one worked perfectly for me.
The challenge is now into adapting it to a sidebar page on google sheet ==> does not work at the moment.
I've been struggling for hours and trying different options, so here is :
- What I made on gs page :
var ss = SpreadsheetApp.getActiveSpreadsheet();
var shEmployees = ss.getSheetByName("Employes");
var colEmploye_nomPrenom=1;
var colEmploye_barcode=colEmploye_nomPrenom+1;
var colEmploye_mail=colEmploye_barcode+1;
var colEmploye_metier=colEmploye_mail+1;
function loadBasicForm(){
var tmp=HtmlService.createTemplateFromFile("basicHtmlForm");
var html = tmp.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
html.setTitle("Test");
SpreadsheetApp.getUi().showSidebar(html);
}//function loadBasicForm(){
function getUnactiveEmployees(){
var ws=shEmployees;
var values= ws.getRange(1,1,ws.getLastRow(),colEmploye_metier).getValues();
var options={};
for (var i=0;i<values.length;i++){
var name=values[i][colEmploye_nomPrenom-1];
var job=values[i][colEmploye_metier-1];
var testUnactive_OK=job=="Désactivé";
if (testUnactive_OK){
options[name]=null;
}//if (testUnactive_OK){
}//for (var i=0;i<values.length;i++){
Logger.log (options);//returns {employee1=null, employee8=null, employee3=null, employee9=null, employee5=null, employee10=null, employee7=null, employee6=null, employee11=null, employee4=null, employee2=null}
return options;
}
What I made on html page :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"><!--Import Google Icon Font-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"><!-- Compiled and minified CSS -->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!--Let browser know website is optimized for mobile-->
</head>
<body>
<div class="container">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input type="text" id="searchedEmployee" class="autocomplete" required><!-- ISSUE AT FILLING IT -->
<label for="searchedEmployee">Spell a Name</label>
</div>
</div><!-- END ROW -->
</div ><!-- END CONTAINER -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <!-- Compiled and minified JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', function() {
google.script.run.withSuccessHandler(populateEmployees).getUnactiveEmployees();
});
function populateEmployees(employees){
var autocomplete = document.getElementById('searchedEmployee');
var instances = M.Autocomplete.init(autocomplete, { data:employees });
}
</script>
</body>
</html>
At this point, the side-page is displayed, but nothing is suggested at typing, for example : "emp" for "employeeX" expected with the "getUnactiveEmployees" list.
EDIT :
My issue is not about displaying - that does displaying.
What I cannot do, is to allow the script to autocomplete the item "searchedEmployee". I guess there is an error on this part :
document.addEventListener('DOMContentLoaded', function() {
google.script.run.withSuccessHandler(populateEmployees).getUnactiveEmployees();
});
Do you have any idea of what I did wrong ?
Many thanks !
Try this:
function loadBasicForm(){
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('basicHtmlForm').setTitle('Test'));
}
I have a Google sheet template. Each time this is opened, I would like to open a Dialog to get two parameters and pass those parameters to a script bound to the Google sheet template. So far I have managed to define and open the Dialog. But the parameters don't show up in the server side script.
It seems like readFormData is not called when I push the "Create" button. If I replace readFormData with google.script.host.close(), the dialog box will close down. But not with readFormData. The same problem goes with close(). So my take on this is the Java script does not execute.
EDIT: I have solved the problem with a workaround. I replaced onclick="readFormData" with onclick="google.script.run.withSuccessHandler(google.script.host.close).getFormData(this.parentNode)" and then everything work as expected. (required a few changes on GS side as well) However, I can't figure out why I can't call my own javascript procedure readFormData(). With help form Chrome Developer Tool I can notice readFormData is not defined, raising an exception "Uncaught ReferenceError: readFormData is not defined". It fires every time i click on the button. So I guess it must be a syntax error that fools the parser or similar.
GS:
function getFormData(obj) {
Logger.log(obj);
return "hello";
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'Create file');
}
function onOpen(e) {
openDialog();
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet"
href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="getSomeData">
<div class="inline form-group">
<label for="fname">Destination</label>
<input type="text" name="fname" style="width: 150px;">
</div>
<div class="inline form-group">
<label for="date">Date</label>
<input type="text" name="date" style="width: 40px;">
</div>
<div>
<input type="button" class = "action" value= "Create" onclick="readFormData()" >
</div>
</form>
<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> -->
<script>
function success(msg) { // I have fixed the ((msg) error
alert(msg);
}
function readFormData(){
console.log("readFormData");
var form = document.getElementById("getSomeData").elements;
var obj ={};
for(var i = 0 ; i < form.length ; i++){
var item = form.item(i);
obj[item.name] = item.value;
}
google.script.run.withSuccessHandler(close).getFormData(obj);
}
function close(){
google.script.host.close();
}
</script>
</body>
</html>
It seems to me there is a misprint on "success" function which could lead to an interpretation problem :
success( ( msg).
Did you try without this "(" ?
I have created a small website using HTML service of Google apps script.
Here is GAS Code
function doGet() {
var t = HtmlService.createTemplateFromFile('form');
t.email=Session.getActiveUser().getEmail();
return t.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
and this is HTML Code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<base target="_top">
</head>
<body onLoad="addEventListeners()">
<div class="container-fluid">
<form id="form1">
<label for="comp_indiv_name" id="company_individual_name" style="display: block" >2. COMPANY NAME</label>
<input type="text" class="form-control" name="cName" required>
<br>
<input type="submit" class="btn btn-primary" value="Create Contract Now">
</form>
</div>
<script>
function addEventListeners() {
var condition=true;
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault();
if(condition==true){condition=false;google.script.run.addData(this);}});
}
</script>
</body>
</html>
HTML page has one form with just one question, and when that form is submitted, the value get written in spreadsheet. Code for that is
function addData(form)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheet=ss.getSheetByName('test');
sheet.getRange(5,5).setValue(form.cName)
htmlPage();
}
All i want is once the value gets written on the sheet, this HTML page gets refreshed automatically. Right now it just stays as it is. Link to the HTML page is https://script.google.com/macros/s/AKfycbzavm6TPFOkIXj_V0uD8XIqMN-9w6jAgp_QgRkJXawFJF59rPU/exec
If you truly want to refresh the page, and not just clear the input field, then I would add a hidden link that has your web app URL, and then programatically "click" it when the server code has completed.
HTML
</form>
<a id="linkToThisWebApp" href="https://script.google.com/macros/s/webAppID/exec" style="display:none">Hidden</a>
<!-- <button onclick="reloadPg()">Test</button> -->
</div>
Script tag - Code with success handler
<script>
function addEventListeners() {
var condition=true;
document.getElementById('form1')
.addEventListener('submit',
function(e){
e.preventDefault();
if(condition==true){
condition=false;
google.script.run
.withSuccessHander(reloadPg)
.addData(this);
}
});
}
window.reloadPg = function() {//Runs when server code has completed
console.log('reloadPg ran');
document.getElementById('linkToThisWebApp').click();//Click the link
}
</script>
I'm just little bit confused on my html code.
What I want just, when user click the circle image, it will call load / take picture and then assign the picture to the circle.
In my below code, it's only call the take picture function, the on change function (pictureselected) is not being called.
When it calls directly through "srcimagefile", all function are called correctly.
Please see my below code. Please advise, what did I miss ?
<html>
<head>
</head>
<body>
<form>
<div class="col-md-12 col-xs-12" align="center">
<div class="outter">
<input type="image" id="imagefile" src="http://lorempixel.com/output/people-q-c-100-100-1.jpg" class="image-circle" onclick="takePicture()"/>
<input type="file" id="srcimagefile" onchange="pictureSelected()" />
</div>
</div>
<div class="group">
<input type="text"><span class="highlight"></span><span class="bar"></span>
<label>Username</label>
</div>
<div class="group">
<input type="password"><span class="highlight"></span><span class="bar"></span>
<label>Password</label>
</div>
<button type="button" class="button buttonBlue">Login
<div class="ripples buttonRipples"><span class="ripplesCircle"></span></div>
</button>
</form>
<link href="userlogincss.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="userloginjs.js"></script>
<script>
function takePicture() {
$("#srcimagefile").click();
}
function pictureSelected() {
fileSelectHandler();
}
// Create variables (in this scope) to hold the Jcrop API and image size
var jcrop_api, boundx, boundy;
function fileSelectHandler() {
// get selected file
var oFile = $('#srcimagefile')[0].files[0];
alert('Hello');
// hide all errors
$('.error').hide();
// check for image type (jpg and png are allowed)
var rFilter = /^(image\/jpeg|image\/png)$/i;
if (! rFilter.test(oFile.type)) {
$('.error').html('Please select a valid image file (jpg and png are allowed)').show();
return;
}
// check for file size
if (oFile.size > 250 * 1024) {
$('.error').html('You have selected too big file, please select a one smaller image file').show();
return;
}
// preview element
var oImage = document.getElementById('imagefile');
var oReader = new FileReader();
oReader.onload = function(e) {
// e.target.result contains the DataURL which we can use as a source of the image
oImage.src = e.target.result;
}
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
</script>
</body>
<html>
You are trying to call the function which will trigger on Change Event. Change your event to "onclick", then your code will execute as expected.
Check the below code change,
<input type="file" id="srcimagefile" onclick="pictureSelected()"
onclick="pictureSelected()"