remove preview image from div - javascript

I Made a Demo for preview image before uploading is as follow.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result).show();
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadphoto").change(function () {
readURL(this);
$('#preview').show();
});
$('#preview').on("click", function () {
$('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
$('#preview').removeProp('src').hide();
$('#uploadphoto').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="uploadphoto" />
<img id="preview" src="">
But Problem is this is work when i have <img id="preview" src="">
What if i wants preview image in div section.
and remove image from div like
<input type="file" id="uploadphoto" />
<!--PREVIEW IMAGE IN THIS DIV-->
<div id="preview">
and after preview delete image on click.
its easy to understand if your answer in fiddle.
thanks.

Check this snippet it helps,
If i understands correctly you want to remove img tag and show image preview in div section.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo('#preview').width(100).height(100);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadphoto").change(function () {
readURL(this);
$('#preview').show();
});
$('#preview').on("click", function () {
$('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
$('#preview').removeProp('src').hide();
$('#uploadphoto').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="uploadphoto" />
<div id="preview"></div>

try with div background-image in jquery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
// $('#preview').attr('src', e.target.result).show();
$('#preview').css("height", "300px");
$('#preview').css("width", "300px");
$('#preview').css("background-image", "url(" + e.target.result + ")").show();
$('#preview').css("background-size","cover");
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadphoto").change(function() {
readURL(this);
$('#preview').show();
});
$('#preview').on("click", function() {
$('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
$('#preview').removeProp('src').hide();
$('#uploadphoto').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="uploadphoto" />
<!--<img id="preview" src="">-->
<div id="preview"></div>

Try this
function Preview_Image_Before_Upload(fileinput_id, preview_id) {
var oFReader = new FileReader();
var fileArray = [];
fileArray.push(document.getElementById(fileinput_id).files[0])
fileArray.forEach(function(entry) {
oFReader.readAsDataURL(fileArray[0]);
});
//console.log(fileArray)
// oFReader.readAsDataURL(fileArray[0]);
oFReader.onload = function(oFREvent) {
if (window.FileReader && window.File && window.FileList && window.Blob) {
var elem = document.getElementById("uploadPreview");
elem.src = oFREvent.target.result;
// document.getElementById("placehere").appendChild(elem);
document.getElementById("uploadPreview").innerHTML=elem;
}
};
};
function removeFns(){
//document.getElementById("uploadPreview").innerHTML=null;
document.getElementById('uploadImage').value = ""
document.getElementById('uploadPreview').src = "#";
}
<input type="file" id="uploadImage" onchange="Preview_Image_Before_Upload('uploadImage', 'uploadPreview');" name="termek_file" class="file_input" />
<img id="uploadPreview" onclick="removeFns()" class="uploadPreview" width="100" />
<div id="placehere" class="uploadPreview" width="100">

you can clear the image by using this code
$("preview").remove()

Related

I got this error in my console: Uncaught (in promise) DOMException: Failed to load because no supported source was found

I'm getting this error when I try to create a JS function where users can preview their files before submit: Uncaught (in promise) DOMException: Failed to load because no supported source was found. I want to create a JS function similar to Twitter where users can preview their image/video files before posting it. But I'm using two inputs instead of one as I'm not sure how it works with only one input. So far, only image files are working. This is the relevant code in my HTML:
<textarea id="autoresizing" name="post"></textarea>
<div class="image-preview" id="imagePreview">
<img src="" class="image-preview__image">
</div>
<div class="video-preview" id="videoPreview">
<video controls loop autoplay muted class="video-preview__video" id="video" src=""></video>
</div>
<br>
<label for="inpFile"><img id="image_icon" src="images/image_icon.png"></label>
<input id="inpFile" type="file" name="file" style="display:none;" accept="image/*">
<label for="inpFile2"><img id="video_icon" src="images/video_icon.png"></label>
<input id="inpFile2" type="file" name="file" style="display:none;" accept="video/*">
<input id="post_button" type="submit" value="Post" style="margin:5px;">
This is the JS function:
//preview image in textarea
const inpFile = document.getElementById("inpFile");
const previewContainer = document.getElementById("imagePreview");
const previewImage = previewContainer.querySelector(".image-preview__image");
inpFile.addEventListener("change", function() {
const file = this.files[0];
if (file) {
const reader = new FileReader();
previewContainer.style.display = "block";
previewImage.style.display = "block";
reader.addEventListener("load", function() {
previewImage.setAttribute("src", this.result);
});
reader.readAsDataURL(file);
} else {
previewImage.style.display = null;
previewImage.setAttribute("src", "");
}
});
// preview video in textarea
const inpFile2 = document.getElementById('inpFile2');
const video = document.getElementById('video');
const previewVideoContainer = document.getElementById("videoPreview");
const previewVideo = previewVideoContainer.querySelector(".video-preview__video");
const videoSource = document.createElement('source');
inpFile2.addEventListener('change', function() {
const file = this.files[0];
if (file) {
const reader = new FileReader();
previewVideoContainer.style.display = "block";
reader.onload = function(e) {
videoSource.setAttribute('src', e.target.result);
video.appendChild(videoSource);
video.load();
video.play();
};
reader.onprogress = function(e) {
console.log('progress: ', Math.round((e.loaded * 100) / e.total));
};
reader.readAsDataURL(file);
} else {
previewVideoContainer.style.display = null;
previewVideoContainer.setAttribute("src", "");
}
});
This works for me using this video: https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm
The filereader for the video has to use readAsArrayBuffer() like suggested here: https://stackoverflow.com/a/61012791/322084
//preview image in textarea
const inpFile = document.getElementById("inpFile");
const previewContainer = document.getElementById("imagePreview");
const previewImage = previewContainer.querySelector(".image-preview__image");
inpFile.addEventListener("change", e => {
let file = e.target.files[0];
if (file) {
let reader = new FileReader();
previewContainer.style.display = "block";
previewImage.style.display = "block";
reader.addEventListener("load", e => {
previewImage.src = e.target.result;
});
reader.readAsDataURL(file);
} else {
previewImage.style.display = "none";
previewImage.src = "";
}
});
// preview video in textarea
const inpFile2 = document.getElementById('inpFile2');
const video = document.getElementById('video');
const previewVideoContainer = document.getElementById("videoPreview");
const previewVideo = previewVideoContainer.querySelector(".video-preview__video");
const videoSource = document.createElement('source');
inpFile2.addEventListener('change', e => {
const file = e.target.files[0];
if (file) {
let reader = new FileReader();
previewVideoContainer.style.display = "block";
reader.addEventListener("load", e => {
let buffer = e.target.result;
let videoBlob = new Blob([new Uint8Array(buffer)], {
type: e.target.filetype
});
let url = window.URL.createObjectURL(videoBlob);
video.src = url;
video.play();
});
reader.addEventListener("progress", e => {
console.log('progress: ', Math.round((e.loaded * 100) / e.total));
});
reader.filetype = file.type;
reader.readAsArrayBuffer(file);
} else {
previewVideoContainer.style.display = null;
previewVideoContainer.src = "";
}
});
<textarea id="autoresizing" name="post"></textarea>
<div class="image-preview" id="imagePreview">
<img src="" class="image-preview__image">
</div>
<div class="video-preview" id="videoPreview">
<video controls loop autoplay muted class="video-preview__video" id="video"></video>
</div>
<br>
<label for="inpFile"><img id="image_icon" src="images/image_icon.png"></label>
<input id="inpFile" type="file" name="file" style="display:none;" accept="image/*">
<label for="inpFile2"><img id="video_icon" src="images/video_icon.png"></label>
<input id="inpFile2" type="file" name="file" style="display:none;" accept="video/*">
<input id="post_button" type="submit" value="Post" style="margin:5px;">
UPDATE
In the following I striped out all the functionality except when selecting an image the video select should be disabled and vice versa. I went for an old-school fieldset that can disable all its children. Alternatively you can just disable the input element itself.
const inpFile = document.getElementById("inpFile");
inpFile.addEventListener("change", e => {
let file = e.target.files[0];
if (file) {
e.target.form.video.disabled = true;
}
});
const inpFile2 = document.getElementById('inpFile2');
inpFile2.addEventListener('change', e => {
const file = e.target.files[0];
if (file) {
e.target.form.image.disabled = true;
}
});
fieldset:disabled label {
opacity: .4;
}
<form name="form01">
<fieldset name="image">
<legend>Pick an image</legend>
<label for="inpFile"><img id="image_icon" src="images/image_icon.png"></label>
<input id="inpFile" type="file" name="file" style="display:none;" accept="image/*">
</fieldset>
<fieldset name="video">
<legend>Pick a video</legend>
<label for="inpFile2"><img id="video_icon" src="images/video_icon.png"></label>
<input id="inpFile2" type="file" name="file" style="display:none;" accept="video/*">
</fieldset>
<input id="post_button" type="submit" value="Post" style="margin:5px;">
</form>

How to Preview Multiple Selected Image [duplicate]

This question already has answers here:
Preview images before upload
(10 answers)
Closed 1 year ago.
I have a code for single Image preview, when we select a file from input field we can see the selected image in preview, but how can i do the same for multiple images preview.
here is my code for single image preview.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview-image')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
<img id="preview-image" class="img-prev rounded" src="#" alt="Upload" onerror=this.src="../assets/images/myfolder/no_image.png" />
<input type="file" name="featured_image" id="customFile" onchange="readURL(this);" required>
Jsfiddle : My Fiddle
You can Check all the things in this answer, and if not cleared, then modify as your need .
$(document).ready(function() {
/*multiple image preview first input*/
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFilesD");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
/*end image preview */
/* Multiple image preview second input*/
$("#mobile").on("change", handleFileSelect);
selDivM = $("#selectFilesM");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
console.log($("#selectFilesM").length);
});
/*multiple image preview*/
var selDiv = "";
// var selDivM="";
var storedFiles = [];
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
var device = $(e.target).data("device");
filesArr.forEach(function(f) {
if (!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function(e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='" + f.name + "' class='selFile' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
if (device == "mobile") {
$("#selectedFilesM").append(html);
} else {
$("#selectedFilesD").append(html);
}
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for (var i = 0, len = storedFiles.length; i < len; i++) {
data.append('files', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handler.cfm', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
function removeFile(e) {
var file = $(this).data("file");
for (var i = 0; i < storedFiles.length; i++) {
if (storedFiles[i].name === file) {
storedFiles.splice(i, 1);
break;
}
}
$(this).parent().remove();
}
#selectedFilesD img,
#selectFilesM img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom: 10px;
}
#userActions input {
width: auto;
margin: auto;
}
#selectFiles img,
#selectedFilesM img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" id="myForm" name="myForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
desktop:
<input data-device="desktop" type="file" id="files" name="files" multiple>
<div id="selectedFilesD"></div>
<br/>
mobile:
<input data-device="mobile" type="file" id="mobile" name="mobile" multiple>
<br/>
<div id="selectedFilesM"></div>
<button type="submit">Submit</button>
</form>

Certain PDF files won't open

I'm having a weird issue I created an app to open PNG and PDF's. The problem is when I try to open PDF files larger than 2,000 Kb it will not display, however PNG's have no problem. I'm confused as too why this is.
<html lang="en"><head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="all" href="styles.css">
</head>
<body>
<ul>
</ul>
<fieldset>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000">
<div>
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="file-select[]" multiple="multiple">
<div id="filedrag" style="display: block;">or drop files here</div>
</div>
<div id="submitbutton" style="display: none;">
<button type="submit">Upload Files</button>
</div>
<div id="sortbutton">
<button type="submit">Submit</button>
</div>
<div id="resetbutton">
<button type="submit">Reset</button>
</div>
</fieldset>
</form>
<div id="messages">
</div>
<script src="filedrag.js"></script>
</body></html>
var files;
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
}
}
// output file information
function ParseFile(file) {
// display an image
if (file.type.indexOf("application") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<object data="' + e.target.result + '"></object></p>');
}
reader.readAsDataURL(file);
}
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" height="500px" width="500px"></p>');
}
reader.readAsDataURL(file);
}
}
function sortFiles() {
files.sort().reverse();
for (var i = 0; i < files.length; ++i) {
Output(files[i]);
}
}
function resetWindow(){
window.location.reload(true)
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton"),
sortbutton = $id("sortbutton"),
resetbutton = $id("resetbutton");
files = new Array();
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.addEventListener("click", sortFiles , false); //style.display = "none";
sortbutton.addEventListener("click", sortFiles , false);
resetbutton.addEventListener("click", resetWindow , false);
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
As I said you try to post a PDF file larger than 2000 Kb it will not display, PNG however will display
I fixed it I hardcoded the path to display the Files
I had the same issue like yours and I resolved in this way:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="height: 100%;">
<button onclick="getFile(event)">Get File</button>
<input id="pdfInputFile" type="file" accept="application/pdf" style="display:none" onchange="loadPDF(this);" />
<object id="pdfViewer" type="application/pdf" style="height:100%; width:100%;border:solid 1px" >
</object>
</body>
<script>
function getFile(e) {
e.preventDefault();
document.getElementById("pdfInputFile").click();
}
function loadPDF(input) {
if (input.files && input.files[0]) {
showFile(input.files[0])
}
}
function showFile(blob){
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
var newBlob = new Blob([blob], {type: "application/pdf"});
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob);
document.getElementById("pdfViewer").setAttribute('data', data);
setTimeout(function(){
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}
</script>
</html>

javascript replace background image in drawingBoard.js

I need to change the background image inside of canvas with the leimi drawingboard.js, but I have no idea how to make it.
I need to show different images so that the user can choose between them with which he is going to work
Here is my form:
<div id="container">
<div class="example" data-example="1"> // THIS DIV IS THE CANVAS
<div class="board" id="default-board"></div> //THIS ID HAVE A IMAGE AND THE CONTROLLERS
</div>
<form class="drawing-form" method="post" name="diagram" id="diagram" enctype="multipart/form-data">
<div id="board"></div>
<input type="hidden" name="image" value="">
<input type="hidden" name="idPac" value="<?php echo $id_paciente; ?>" />
<input type="hidden" name="idDoc" value="<?php echo $user_id; ?>" />
<br><hr>
<button class="btn btn-info" id="btnUpload"><?php $translate->__('Save Diagram'); ?></button>
</form>
<div id="ldiag" style="display:none;"><img src="images/loading4.gif" /></div>
</div>
And the javascript code is:
<script src="js/drawingboard.min.js"></script>
<script data-example="1">
var defaultBoard = new DrawingBoard.Board("default-board", {
background: "imagenes/canvas/cara.jpg", //THIS IS THE IMAGE I NEED TO CHANGE FOR OTHERS IF NEEDED, EXAMPLE /pie.png, /cuerpo.png
droppable: true,
webStorage: false,
enlargeYourContainer: true,
addToBoard: true,
stretchImg: false
});
defaultBoard.addControl("Download");
$(".drawing-form").on("submit", function(e) {
var img = defaultBoard.getImg();
var imgInput = (defaultBoard.blankCanvas == img) ? "" : img;
$(this).find("input[name=image]").val( imgInput );
defaultBoard.clearWebStorage();
});
$(function() {
$("#file-input").change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var $img = $("<img>", { src: e.target.result });
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
</script>
<script src="js/yepnope.js"></script>
<script>
var iHasRangeInput = function() {
var inputElem = document.createElement("input"),
smile = ":)",
docElement = document.documentElement,
inputElemType = "range",
available;
inputElem.setAttribute("type", inputElemType);
available = inputElem.type !== "text";
inputElem.value = smile;
inputElem.style.cssText = "position:absolute;visibility:hidden;";
if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
available = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== "textfield" &&
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
}
return !!available;
};
yepnope({
test : iHasRangeInput(),
nope : ["css/fd-slider.min.css", "js/fd-slider.min.js"],
callback: function(id, testResult) {
if("fdSlider" in window && typeof (fdSlider.onDomReady) != "undefined") {
try { fdSlider.onDomReady(); } catch(err) {}
}
}
});
</script>

How to minimize code based on selector in jQuery

jQuery script code:
$(function() {
$('#html_btn1').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview1(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
$('#html_btn2').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview2(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
$('#html_btn3').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview3(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
function showimagepreview1(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#cu1').attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
function showimagepreview2(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#cu2').attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
function showimagepreview3(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#cu3').attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
});
HTML markup:
<div class="form-group">
<img id="cu1" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="html_btn1" />
<img id="cu2" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="html_btn2" />
<img id="cu3" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="html_btn3" />
</div>
Above code works fine whenever I am trying to upload image it checks validate and preview the image
But I want to minimize my code as only one change function and only one showimagepreview function
Please give me an idea how to achieve?
#Huangism is correct, this should probably be on codereview. But, for the sake of helping:
$(function() {
// combine binding selector in to one
$('#html_btn1,#html_btn2,#html_btn3').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview(this); break; // change to single "showimagepreview" function
default : $('#errorimg').html("Invalid Photo"); break;
}
});
function showimagepreview(input) {
// grab "cu#" using the original element's id
var cu_id = '#cu' + input.id.match(/\d+$/)[0];
/* alt: var cu_id = input.id.replace('html_btn','#cu'); */
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
// reference id here
$(cu_id).attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
});
Combine your bindings in to one using a comma-separated selector
Remove the duplicated showimagepreview# methods and unify into one function
Change hard-coded cu# ids in to a dynamic id based on the original input's ID.
Reference that id in the selector.
Would it not be easier to use a class? As long as you are keeping the scope by using 'this'
You should be fine to have two generic functions like so
$('.addClassToImages').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview3(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
function showimagepreview1(input) {
var cu_id = '#cu' + input.id.match(/\d+$/)[0];
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$(cu_id).attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
HTML:
<div class="form-group">
<img id="cu1" src="upload-photo-img.jpg"/>
<input class="addClassToImages" type="file" path="images" id="html_btn1" />
<img id="cu2" src="upload-photo-img.jpg"/>
<input class="addClassToImages" type="file" path="images" id="html_btn2" />
<img id="cu3" src="upload-photo-img.jpg"/>
<input class="addClassToImages" type="file" path="images" id="html_btn3" />
</div>
Javascript:
$(function() {
$('input[type=file]').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' : showimagepreview(this); break;
case 'gif' :
case 'jpeg' : showimagepreview(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
function showimagepreview(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#cu'+input.id).attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
});
HTML:
<div class="form-group">
<img id="cu1" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="1" />
<img id="cu2" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="2" />
<img id="cu3" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="3" />
EDIT - UPDATED LINK
http://jsfiddle.net/S4mk2/
And... yes as Brad Christie mentioned, this would be ideal for HTML5

Categories