how to call function and access in innerHTML - javascript

I'd like to show data which stored in DB at update page.
My problem is that I wanna access innerHTML tag to show images and any other data like
document.getElementById(visibilities).checked = true;
or
for (i=0; i<files.length; i++) {
var image = new Image();
image.src = files[i];
image.height = 100;
display.appendChild(image);
}
Btw, I don't know how to access tags or call function with onload in innerHTML. Please let me know. Thanks in advance.
function getData(id) {
var path = '/project/update/' + id;
restfull.get({
path: path
}, function(err, data) {
if(err) return;
var title = data.title;
var descriptions = data.descriptions;
var visibilities = data.visibilities;
var files = data.image;
const modal = new window.Modal({
modalContainerId: 'updateModal'
, modalTitleText: `Update Your Project`
, modalContentsInnerHTML: ` <form method="put" id="updateform" enctype="multipart/form-data" onload='getData()'>
<input type="radio" name="visibilities" value="public" id="public">Public
<input type="radio" name="visibilities" value="private" id="private">Private
<input type="radio" name="visibilities" value="unlisted" id="Unlisted">Unlisted <br>
<label for="title">Project Title</label>
<input type="text" name="title" id="title" required value="${title}"><br>
<label for="descriptions">Description</label>
<input type="text" name="descriptions" id="descriptions" required value="${descriptions}"><br>
<label for="multi_image">Images/ Videos
<input type="file" id="multi_image" name="multi_image" multiple onchange='previewImages()'><br>
<div id="display"></div>
<div id="projectpreview"></div>
</form>`
, modalSubmitBtnText: 'Update'
, modalSubmitBtnAction: function(){updatesubmit(data._id)}
, modalCancelBtnText: 'Cancel'
, modalCancelBtnAction: function() {
modal.destroy();
}
})
modal.show();
})
}

You can define the function outside and reference it by name. Here I also use the dataset of the button inside the innerHTML to store the id I want to access when the function is called.
const id = 1
document.getElementById('container').innerHTML = `
<button data-selected="${id}" onclick="foo(event)">Click Me</button>
`
const foo = ({target}) => console.log('selected id:', target.dataset.selected)
<div id="container"></div>

If you want to preview the uploaded image for update:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]); // convert to base64 string
}
}
$("#imgInput").change(function() {
readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form runat="server">
<input type='file' id="imgInput" />
<img id="preview" src="#" alt="your image" />
</form>
If you want to display an already stored image from database:
var image = document.getElementById('preview');
image.src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==";
image.width=100;
image.height=100;
image.alt="here should be some image";
<img id="preview">

Related

How clear the form inputs after submission?

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>

How do I upload multiple files using Firebase?

$("#fileButton1, #fileButton2, #fileButton3").on("change", function(event) {
selectedFile = event.target.files[0];
});
function uploadFile() {
var filename = selectedFile.name;
var storageRef = firebase.storage().ref('/files_new/' + filename);
var uploadTask = storageRef.put(selectedFile);
uploadTask.on('state_changed', function progress(snapshot){
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
}, function () {
window.location.href = "uploadThumbnail.html";
});
}
<form class="upload-form">
<progress value="0" max="100" id="uploader">0%</progress>
<input value="upload" id="fileButton1" class="choose-file-btn" type="file">
<input value="upload" id="fileButton2" class="choose-file-btn" type="file">
<input value="upload" id="fileButton3" class="choose-file-btn" type="file">
<button type="button" class="submit-btn" onclick="uploadFile()">Continue</button>
</form>
The code above uploads only one file even though I select multiple. How can I make it to push all
files that are selected.
As per the comments i understood you want multiple input files and you want to send all at a time
Follow this and play with your requirement by keeping the below code as reference
$(document).ready(function(){
var filesList = [],
paramNames = [],
elem = $("form");
file_upload = elem.fileupload({
formData:{extra:1},
autoUpload: false,
fileInput: $("input:file"),
}).on("fileuploadadd", function(e, data){
filesList.push(data.files[0]);
paramNames.push(e.delegatedEvent.target.name);
});
$("button").click(function(e){
e.preventDefault();
file_upload.fileupload('send', {files:filesList, paramName: paramNames});
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/echo/json/" method="POST">
<input name="file1[]" type="file" multiple />
<br /> <br />
<input name="file2[]" type="file" multiple />
<br /> <br />
<input name="file3[]" type="file" multiple />
<br /> <br />
<button>send by fileupload send api</button>
</form>
You can choose multi files in one input file here
You can save all of the selected files to an array before uploading:
var selectedFiles = [];
$("#fileButton1, #fileButton2, #fileButton3").on("change", function(event) {
var id = $(this).prop('id');
var item = selectedFiles.find(x => x.id === id);
if (!item) {
// if the array doesn't contain any file with this id
// try to push an object which contains id and the file to the array
selectedFiles.push({
id: id,
file: event.target.files[0]
});
} else {
// if the array already contains some file with this id
// try to update the file
item.file = event.target.files[0];
}
});
function uploadFile() {
// uploading file one-by-one
for (var item of selectedFiles) {
var filename = item.file.name;
var storageRef = firebase.storage().ref('/files_new/' + filename);
var uploadTask = storageRef.put(item.file);
uploadTask.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
}, function() {
window.location.href = "uploadThumbnail.html";
});
}
}

Replace uploaded image with placeholder image permanently

I've been trying to give functionality of replacing image with my uploaded placeholder image so that my client's don't need to login at the backend of (any CMS) and almost all of them are non-techies.
The following piece of code below will display the placeholder image along with the "upload file button". Once they upload their image, I will delete the choose file option. Is there any possibility of storing their uploaded image somewhere in the folder of the website?
HTML:
<input type='button' id='remove' value='remove' class='hide'/>
<input type='file' id="imgInp" /><br>
<img width="230px" id="blah" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png" alt="your image" />
JS:
$('#blah').show();
$('#remove').hide();
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
if( $('#imgInp').val()!=""){
$('#remove').show();
$('#blah').show('slow');
}
else {
$('#remove').hide();
$('#blah').hide('slow');
}
readURL(this);
});
$('#remove').click(function(){
$('#imgInp').val('');
$(this).hide();
$('#blah').hide('slow');
$('#blah').attr('src','http://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png');
});
Check out here JSFIDDLE
try using this
<input id="src" type="file"/>
<input type="button" id="rem" value="remove" style="visibility:hidden;" onclick="myfun()">
<img id="target" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png" style="width:100px;height:100px;"/>
<script>
function showImage(src,target) {
var fr=new FileReader();
fr.onload = function(e) { target.src = this.result; };
src.addEventListener("change",function() {
fr.readAsDataURL(src.files[0]);
document.getElementById("src").style.visibility = "hidden";
document.getElementById("rem").style.visibility = "visible";
});
}
var src = document.getElementById("src");
var target = document.getElementById("target");
showImage(src,target);
function myfun(){
target.src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png";
document.getElementById("src").style.visibility = "visible";
document.getElementById("rem").style.visibility = "hidden";
};
</script>

How can I target the response from an ajax to a specific div that was clicked

I am trying to get an image loaded and displayed in a particular
slot depending on where I click, Say view1, view2 or view3 as shown below.
I have set up a form with div elements and I want to use ajax to
post and process a browsed image that I select using the
How can I pass the appropriate target: id name to the JavaScript to
display the image in the correct location? My scripts are shown below.
<form class = "ajaxform" method="post"
enctype = "multipart/form-data"
action = 'upload.php'>
<div id='view1' onclick="triggerFileUpload('photo')>view1</div>
<div id='view2' onclick="triggerFileUpload('photo')>view2</div>
<div id='view3' onclick="triggerFileUpload('photo')>view3</div>
<input type="file" name="imagefile" id="photo" />
</form>
<script type="text/javascript" >
$(document).ready(function() {
$('#photo').live('change', function() {
$(".ajaxform").ajaxForm({
target: '#view'
}).submit();
});
});
</script>
<script type="text/javascript">
function triggerFileUpload(f){
document.getElementById(f).click();
}
</script>
jsfiddle
You can attach events to the target divs using jQuery's click method and get the id from event.target.id. I'm not sure of the specifics of what you are trying to do, but I hope something along the lines of the following will suffice.
HTML
<form class = "ajaxform" method="post"
enctype = "multipart/form-data"
action = 'upload.php'>
<div id='view1' class='photo-target'>view1</div>
<div id='view2' class='photo-target'>view2</div>
<div id='view3' class='photo-target'>view3</div>
<input type="file" name="imagefile" id="photo" />
</form>
JavaScript
function createObjectURL(object) {
return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}
function revokeObjectURL(url) {
return (window.URL) ? window.URL.revokeObjectURL(url) : window.webkitURL.revokeObjectURL(url);
}
$(document).ready(function() {
var photoTarget = null;
$('#photo').on('change', function(event) {
var src = createObjectURL(this.files[0]);
var image = new Image();
image.src = src;
image.onload = function() {
revokeObjectURL(this.src);
};
$("#" + photoTarget).append(image);
$(".ajaxform").ajaxForm({
target: '#view'
}).submit();
});
$('.photo-target').click(function (event) {
photoTarget = event.target.id;
$("#photo").click();
});
});

ajax image upload with pre-preview

I am uploading image with ajax and showing image before uploading with jquery.
here is my html code
<form id="uploadimageS2" action="" method="post" enctype="multipart/form-data">
<div id="image_previewS2"><img id="previewingS2" src="img/noimage.png" /></div>
<div id="selectImageS2">
<label>Select Your Image</label><br/>
<input type="file" name="fileS2" id="fileS2" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
then here is my jquery code
// Function to preview image
$("#fileS2").change(function() {
$("#messageS2").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewingS2').attr('src','img/noimage.png');
$("#messageS2").html("<p id='errormsg'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
function imageIsLoaded(e) {
$('#image_previewS2').css("display", "block");
$('#previewingS2').attr('src', e.target.result);
$('#previewingS2').attr('width', '250px');
$('#previewingS2').attr('height', '230px');
};
reader.readAsDataURL(this.files[0]);
var file = this.files[0];
here i want to add another element instead of "this". because i am uploading 3 images in one page and when using this script it is going wired.
i already tried
reader.readAsDataURL($(#uploadimageS2).files[0]);
reader.readAsDataURL($(#fileS2).files[0]);
and those didn't work.

Categories

Resources