Delete image preview before upload - javascript

I am uploading multiple images and showing preview, it is working fine. When I want to delete a particular preview image the preview image is deleted but when I upload all the files are uploading. Please check.
My form:
<div class="form-group">
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-5">
Upload a file(.csv,.xls,.xlsx)
</div>
<div class="col-sm-12 col-md-6 col-lg-7">
<input type="file" class="form-control" id="gallery-photo-add" name="projectfile[]" multiple>
<div class="gallery">
</div>
</div>
</div>
</div>
Javascript
$(function() {
var imageArray = [];
var imagesPreview = function(input, placeToInsertImagePreview) {
var data = '';
if (input.files) {
var filesAmount = input.files.length;
for (let i = 0; i < filesAmount; i++) {
data +='<li>'+ input.files[i].name + '</li>';
var reader = new FileReader();
reader.onload = function(event) {
var image = '<a class="delete" data-value='+ i +'><img class="images" src='+ event.target.result +'><i class="fas fa-times closeicon" aria-hidden="true"></i> </a>';
$($.parseHTML(image))
.appendTo(placeToInsertImagePreview);
}
// console.log(input.files);
reader.readAsDataURL(input.files[i]);
imageArray.push(input.files[i]);
console.log(imageArray);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
$("div.gallery").on('click','.delete',function(){
// console.log($(this).data("value"));
$(this).remove();
imageArray.splice($(this).data("value"),1);
console.log(imageArray);
});
});

Multiple input type file return a read-only fileList. It contains a collection of File objects. Therefore u can't simply remove an element from this list.
You have to use AJAX to handling the Form. Referthis question.

Related

Problem selecting file when I want to create multiple input type = 'file'

I want to create multiple images for an item. The problem I have is that when I click on the Add button, the input type = 'file' tag is created, but when I click on the created tag, it does not work and only the first option that was initially available works.
in Html
<button type="button" id="bAddImage"> Add </button>
<div class="m-t-15" id="row-file">
<div class="row-file-upload">
<div class="col-lg-6 col-md-6 m-t-10 row clearfix">
<button class="material-icons text-center bClear waves-effect bg-blue-grey">clear</button>
<div class="file-upload">
<div class="file-select">
<div class="file-select-name fileName">Choos File</div>
<div class="file-select-button">... Choose File</div>
<input type="file" class="chooseFile">
</div>
</div>
</div>
</div>
in Script
<script type="text/javascript">
$(document).ready(function () {
$('body').on('click',
'.bClear',
function (event) {
event.preventDefault();
var $el = $('.chooseFile');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();
$('.chooseFile').trigger('change');
});
$('body').on('change', '.chooseFile', function () {
var filename = $(".chooseFile").val();
if (/^\s*$/.test(filename)) {
$(".file-upload").removeClass('active');
$(".fileName").text("فایل انتخاب نشده");
}
else {
$(".file-upload").addClass('active');
filename = filename.replace("C:\\fakepath\\", "");
if (filename.length > 30) {
filename = filename.substring(0, 30) + '...';
}
$(".fileName").text(filename);
}
});
$('body').on('click', '#bAddImage', function () {
$('#row-file').append($('.row-file-upload').html());
});
});
</script>
this is a simple Example for dynamically adding fileinput to HTML.
$(document).ready(function() {
var wrapper = $(".wrapper");
var add_button = $(".Add");
var uploadField = document.getElementById("file");
$(add_button).click(function(e) {
e.preventDefault();
$(wrapper).append('<div><input type="file" name="att"/>Remove</div>');})
$(wrapper).on("click", ".remove", function(e) {
e.preventDefault();
$(this).parent('div').remove();});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
+ Add
<div>
<input type="file" id="file" name="att">
</div>
</div>

Preview image displaying only name when getting the file type dynamically

I am displaying file type dynamically on clicking on the anchor tag. I am able to preview the image in the first file type but not able to preview in the second file type which is displaying dynamically. I am getting only the image name.
I am getting the output.
Check this below image. In the first file type image displaying but in the second file type, the only name is displaying.
Would you help me out with this?
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(document).on('click', '#addMoreEntry', function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(".work").append("<div class='workBoxFormWrapper form-bottom-border'><h3 class='text-red text-upper'>Entry 1</h3><div class='row'><div class='col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12'> <span>Please upload the image</span><div class='insert-img d-table'> <img src='https://www.rabata.org/wp-content/uploads/2018/05/dummy.png' alt='user-img' class='show-uploaded-img'><div class='d-table-cell findbrowse'> <input type='file' name='work_pic[]' class='work_pic'><label for='work_pic' class='text-underline openbrowse'> Upload</label></div></div></div></div></div>")
}
});
//Once remove button is clicked
$('.work').on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
function workimage_preview(input) {
if (input.files && input.files[0]) {
var $input = $(input);
var reader = new FileReader();
reader.onload = function(e) {
$input.closest('.workBoxFormWrapper').find('.show-uploaded-img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".work_pic").change(function() {
workimage_preview(this);
//alert('hello');
});
<div class="work">
<div class='workBoxFormWrapper form-bottom-border'>
<h3 class='text-red text-upper'>Entry 1</h3>
<div class='row'>
<div class='col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12'> <span>Please upload the image</span>
<div class='insert-img d-table'> <img src='https://www.rabata.org/wp-content/uploads/2018/05/dummy.png' alt='user-img' class='show-uploaded-img'>
<div class='d-table-cell findbrowse'> <input type='file' name='work_pic[]' class='work_pic'> <label for='work_pic' class='text-underline openbrowse'> Upload</label></div>
</div>
</div>
</div>
</div>
</div>
+ Click to add more entry
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
When you add the listener the dynamic inputs not exist yet, so they not have this listener.
What you can do is add to them onchange="myfunction(this)" as below:
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(document).on('click', '#addMoreEntry', function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(".work").append("<div class='workBoxFormWrapper form-bottom-border'><h3 class='text-red text-upper'>Entry 1</h3><div class='row'><div class='col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12'> <span>Please upload the image</span><div class='insert-img d-table'> <img src='assets/images/upload-img.png' alt='user-img' class='show-uploaded-img'><div class='d-table-cell findbrowse'> <input type='file' name='work_pic[]' class='work_pic' onchange='workimage_preview(this)'><label for='work_pic' class='text-underline openbrowse'> Upload</label></div></div></div></div></div>")
}
});
//Once remove button is clicked
$('.work').on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
function workimage_preview(input) {
if (input.files && input.files[0]) {
var $input = $(input);
var reader = new FileReader();
reader.onload = function(e) {
$input.closest('.workBoxFormWrapper').find('.show-uploaded-img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".work_pic").change(function() {
workimage_preview(this);
//alert('hello');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="work">
<div class='workBoxFormWrapper form-bottom-border'>
<h3 class='text-red text-upper'>Entry 1</h3>
<div class='row'>
<div class='col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12'> <span>Please upload the image</span>
<div class='insert-img d-table'> <img src='assets/images/upload-img.png' alt='user-img' class='show-uploaded-img'>
<div class='d-table-cell findbrowse'> <input type='file' name='work_pic[]' class='work_pic'> <label for='work_pic' class='text-underline openbrowse'> Upload</label></div>
</div>
</div>
</div>
</div>
</div>
+ Click to add more entry

javascript preview image before upload

I made a code in the img box in sequence. However, if the if (file.size > 1M) is large, a space occurs in the img box.
How do I get the next image to come in without spaces?
**
javascript preview image before upload
**
<form class="my_form">
<input type="file" id="fileElem" multiple accept="image/*"
onchange="handleFiles(this.files)">
<label class="button" for="fileElem">Select Images</label>
<div id="gallery">
<img id="**imgg0**" class="imgg">
<img id="**imgg1**" class="imgg">
<img id="**imgg2**" class="imgg">
<img id="**imgg3**" class="imgg">
<img id="**imgg4**" class="imgg">
</div>
</form>
<script>
function handleFiles(files) {
var files = [...files]
var imgs = document.querySelectorAll('img');
files.forEach(function(file, index){
if(file.size > 1000000){
delete file[index];
} else{
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function() {
var img = **document.getElementById('imgg'+index)**;
img.src = reader.result;
}
}
})
}
</script>
[enter image description here][1]
[1]: https://i.stack.imgur.com/0dJ45.png
Check my solution.
function handleFiles(files) {
var imgs = document.querySelectorAll('img');
//Image element undex
let imgIndex=0;
//Loop through all the images
for(var i = 0; i < files.length; i++){
var reader = new FileReader();
reader.onload = function(e) {
var img = document.getElementById('imgg'+imgIndex);
img.src = e.target.result;
imgIndex++;
}
reader.readAsDataURL(files[i]);
}
}
<form class="my_form">
<input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
<label class="button" for="fileElem">Select Images</label>
<div id="gallery">
<img id="imgg0" width="10%" class="imgg">
<img id="imgg1" width="10%" class="imgg">
<img id="imgg2" width="10%" class="imgg">
<img id="imgg3" width="10%" class="imgg">
<img id="imgg4" width="10%" class="imgg">
</div>
</form>
a simple solution for multi-image previews. This creates img placeholders dynamically for as many pictures selected in file control
<div id="container01"></div>
<input id="filer" type="file" onchange="preview()" multiple="multiple" />
<script>
function preview() {
var element = document.getElementById("container01");
for (var i = 0; i < event.target.files.length; i++) {
var imgi = document.createElement('img'); // variable imgi has i loop counter
imgi.src = URL.createObjectURL(event.target.files[i]);
imgi.style.width = "100px";
imgi.style.height = "100px";
element.appendChild(imgi); // add new preview to container
var space = document.createTextNode(" "); // spacer between imgs
element.appendChild(space); // add space for horizontal preview
// var linebreak = document.createElement('br'); // add line break <br/>
// element.appendChild(linebreak);
}
}
</script>

Delete image when upload mutiple file in laravel is not working

i/m doing delete image when the client upload multiple image and preview that image. here is my html
<div class="form-group">
<input id="image" class="" name="image[]" type="file" multiple />
<div class="preview clearfix">
</div>
<div class="upload-img">
<label for="image">
<u>Upload</u>
</label>
</div>
</div>
and here is my JS to upload image and preview images
$("#image").change(function(){
var total_file = document.getElementById('image').files.length;
for(var i = 0; i < total_file ; i++){
var html =
"<div class='img pull-left'>"
+"<img class='preview-img' data-id='"+i+"' id='preview-img-"+i+"' src='"+URL.createObjectURL(event.target.files[i])+"'>"
+"<img class='delete-img' image-id='#preview-img-"+i+"' src='{{ url('/media/error.svg')}}'>"
+'</div>';
$('.preview').append(html);
};
});
$(document).on('click', '.delete-img', function() {
var img = $(this).attr('image-id');
var id_img = $(img).attr('data-id');
var total_files = document.getElementById('image').files;
$(this).closest('.img').remove();
delete total_files[id_img];
});
my problem is delete image in UI but do not delete element image. I want to delete both DOM HTML and file exist in

Jquery, image showing after change input

Anyone can show me what is wrong with my code? It show picture after change input but still in first input
It changes only first input everytime
Here is the code
$(document).ready(function() {
function readURL(input, data) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var blah = '#blah' + data;
$(blah).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".active_file").change(function() {
var data = $(this).data('im');
var img_div = '#img_div' + data;
var img_id = '#image_id' + data;
$(img_id).html('<img id="blah' + data + '" src="#" alt="your image" />');
alert(data);
readURL(this, data);
data = data + 1;
$(this).removeClass('active_file');
$(img_div).after('<div class="col-md-2 img_div" id="img_div' + data + '" ><input form="formid" name="file" type="file" id="fileI" class="inputfile active_file" data-im=' + data + '><label class="col-md-12 image " for="fileI" id = "image_id' + data + '"> <i class="fa fa-cloud-upload"></i><br>Nahrať obrázok..</label></div>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-6 gallery">
<div class="row galeria_row">
<div class="col-md-2 img_div" id="img_div1">
<input form="formid" name="file" type="file" id="fileI" class="inputfile active_file" data-im='1'>
<label class="col-md-12 image " for="fileI" id="image_id1"> <i class="fa fa-cloud-upload"></i>
<br>Nahrať obrázok..</label>
</div>
</div>
</div>
</div>
You need to use delegate event of jQuery because your DOM is being updated in real time.
So instead of doing:
$(".active_file").change(function() {
do this
$(document).on('change', '.active_file', function(){
$(document).ready(function(){
function readURL(input,data) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var blah = '#blah' + data;
$(blah).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).on('change', '.active_file', function(){
var data = $(this).data('im');
var img_div = '#img_div' + data;
var img_id = '#image_id' + data;
$(img_id).html('<img id="blah'+data+'" src="#" alt="your image" />');
alert(data);
readURL(this,data);
data = data + 1;
$(this).removeClass('active_file');
$(img_div).after('<div class="col-md-2 img_div" id="img_div'+data+'" ><input form="formid" name="file" type="file" id="fileI" class="inputfile active_file" data-im='+data+'><label class="col-md-12 image " for="fileI" id = "image_id'+data+'"> <i class="fa fa-cloud-upload"></i><br>Nahrať obrázok..</label></div>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-6 gallery">
<div class="row galeria_row">
<div class="col-md-2 img_div" id="img_div1" >
<input form="formid" name="file" type="file" id="fileI" class="inputfile active_file" data-im='1'>
<label class="col-md-12 image " for="fileI" id = "image_id1"> <i class="fa fa-cloud-upload"></i>
<br>Nahrať obrázok..</label>
</div>
</div>
</div>
</div>

Categories