Image Upload with preview and Delete option - Javascript / Jquery - javascript

I have code below that runs perfectly and uploads multiple images.
This is the html and jQuery code:
<div class="field" align="left">
<span>
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple />
</span>
</div>
The script is as below:
<style>
input[type="file"] {
display:block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
margin: 10px 10px 0 0;
padding: 1px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
if(window.File && window.FileList && window.FileReader) {
$("#files").on("change",function(e) {
var files = e.target.files ,
filesLength = files.length ;
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<img></img>",{
class : "imageThumb",
src : e.target.result,
title : file.name
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
The code adds multiple images and shows previews of the images too. But now I want that when a user clicks on some button, lets say delete on every image uploaded, it should be removed. Not hidden.
Any help to this will be appreciated!

Try adding this : .click(function(){$(this).remove();});. It will remove the image by clicking it.
EDIT Improved version included.
EDIT 2 Since people keep asking, please see this answer on manually deleting a file from a FileList (spoiler: it's not possible...).
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
// Old code here
/*$("<img></img>", {
class: "imageThumb",
src: e.target.result,
title: file.name + " | Click to remove"
}).insertAfter("#files").click(function(){$(this).remove();});*/
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple />
</div>

Use this for remove files values and file preview
$(".remove").click(function(){
$(this).parent(".pip").remove();
$('#files').val("");
});`

Related

How can i delete images preview each time file input is clicked?

I'm trying to reset the image preview created by file input each time the upload button clicks. I'm new to JS so forgive me if I missed the obvious.
This is a code snippet I found to show the preview:
$(function() {
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img class="padit">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
This is my HTML:
<div class="upload-field">
<label class="bcard-label" for="gallery-photo-add">
<input id="gallery-photo-add" type="file" accept="image/*" value="" multiple>
<i class="fa fa-2x fa-camera"></i>
</label>
</div>
<div class="gallery">
</div>
This is the CSS:
.upload-field{
display: flex;
justify-content: center;
align-items: center;
max-width: 95%;
border: 4px dashed grey;
height: 100px;
margin: auto;
}
.gallery{
display: inline-block;
column-count: 2;
margin: 15px;
}
img.padit{
padding: 5px;
}
And with my very little knowledge in JS I tried to complete the task with this snippet:
const element = document.getElementById("gallery-photo-add");
element.addEventListener("click", function() {
document.getElementById("padit").remove();
Any ideas where am I wrong?
Thanks :)

drag and drop file did not response

I am trying to do a upload file and drag & drop file but only the upload file was successfully and the drag & drop did not function and I can't figure it out. Below is my code:
HTML
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet"
/>
<label for="file-input">
<i onclick="" class="material-icons md-36">upload_file</i>
</label>
<input
onclick="uploadFiles()"
id="file-input"
type="file"
multiple="true"
accept=".docx,.pdf,.jpg,.jpeg,.png"
/>
CSS
.material-icons.md-36 {
font-size: 36px;
color: #65daff;
position: absolute;
top: 47.6%;
right: 16.67%;
left: 11.67%;
cursor: pointer;
user-select: none;
}
#file-input {
display: none;
visibility: none;
}
JavaScript
function uploadFiles() {
var files = document.getElementById("file-input").files;
if (files.length == 0) {
alert("Please first choose or drop any file");
return;
}
var filenames = "";
for (var i = 0; i < files.length; i++) {
filenames += files[i].name + "\n";
}
alert("Selected file: " + filenames);
}
You need to have drag and drop handler. This code is taken from the doc . I added a wrapper div to handler drag and drop. Two events to handle this is ondrop to handle file drop and ondragover just to prevent default behaviour of file dragging
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
function uploadFiles() {
var files = document.getElementById("file-input").files;
if (files.length == 0) {
alert("Please first choose or drop any file");
return;
}
var filenames = "";
for (var i = 0; i < files.length; i++) {
filenames += files[i].name + "\n";
}
alert("Selected file: " + filenames);
}
function dragOverHandler(ev) {
console.log('File(s) in drop zone');
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
}
function dropHandler(ev) {
console.log('File(s) dropped');
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
// If dropped items aren't files, reject them
if (ev.dataTransfer.items[i].kind === 'file') {
var file = ev.dataTransfer.items[i].getAsFile();
alert("Selected file: " + file.name);
}
}
} else {
// Use DataTransfer interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.files.length; i++) {
console.log('... file[' + i + '].name = ' + ev.dataTransfer.files[i].name);
}
}
}
.material-icons.md-36 {
font-size: 36px;
color: #65daff;
top: 47.6%;
right: 16.67%;
left: 11.67%;
cursor: pointer;
user-select: none;
}
#file-input {
display: none;
visibility: none;
}
#drop_zone {
position: relative;
background: #2D2D2D;
padding: 10px;
height: 50vw;
width: 50vw;
display: flex;
justify-content: center;
align-items: center;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
<label for="file-input">
<i onclick="" class="material-icons md-36">upload_file</i>
</label>
<input onclick="uploadFiles()" id="file-input" type="file" multiple="true" accept=".docx,.pdf,.jpg,.jpeg,.png" />
</div>

I want to save textbox to .txt file in HTML using JavaScript but I have an error

I have a fake web site for a school project and I want to get the HTML code to send the information from textbox to .txt file with Javascript, but it doesn't work and I don't know why. Can you tell me where the error is, please?
<section>
<form method:"POST">
<label>Escrigui el seu usuari:</label>
<input type="text" name="usuari" id="usuari" size="20"/>
<label>Escrigui la seva contrasenya:</label>
<input type="text" name="contrasenya" id="contrasenya" size="20"/>
<input type="button" value="submit" id="button" href="" onclick="WriteToFile()"/>
</form>
<script type="text/javascript">
function WriteToFile(passForm){
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("filename.txt", True);
var usuari = document.getElementById("usuari").value;
var contrasenya = document.getElementById("contrasenya").value;
s.writeline("usuari :" + usuari);
s.writeline("contrasenya :" + contrasenya);
s.writeline("-----------------------------");
s.Close();
}
</script>
I've programmed a "Notebook" that exports the input to a txt file which is ready to be downloaded after:
<html><head>
<style>
body {
margin: 0%;
}
#font-face {
font-family: "CG";
src: url(./resources/CENTURYGOTHIC.ttf) format("truetype");
}
textarea {
margin-left: 0%;
margin-top: 0%;
height: 80%;
width: 100%;
resize: none;
visibility: visible;
background-color: white;
border-color: black;
}
button {
background-color: white;
font-family: CG;
border-color: black;
border-width: 1px;
padding-top: 10px;
padding-bottom: 10px;
padding-right: 20px;
padding-left: 20px;
margin-top: 10px;
text-transform: capitalize;
}
</style></head>
<body>
<textarea id="textbox" placeholder="You can write anything here... just start tyipng what you would like to remember: Notes, Homework, Tests, just anything."></textarea>
<button id="create">SAVE TO FILE</button>
<a download="notes.txt" id="downloadlink" style="display: none"><button onclick="functionreset()">DOWNLOAD</button></a>
<br>
<script>
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function() {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
document.getElementById('create').style.display = 'none';
}, false);
})();
function functionreset() {
var link = document.getElementById('downloadlink');
link.style.display = 'none';
document.getElementById('create').style.display = 'block';
}
</script>
<script>
document.getElementById("textbox").onchange = function() {functionreset()}
</script>
<!-- <iframe height=100% width=100%; src=./test.html></iframe>-->
</body></html>
maybe you can use fragments of this...
Notify me if it worked😉

How to remove selected image from preview and as well as from url variable before uploading it

I have the code for the image preview but after removing it only goes from preview but not from url variable and the removed images url are also being stored in database.
I'm using Spring Boot for controllers.
how to remove the image while clicking the remove button and also uploaded link from the uploaded files list
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\"title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
<style>
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
</style>
</head>
<body>
<div class="field" align="left">
<h3>Upload your images</h3>
<input type="file" id="files" multiple="multiple" />
</div>
</body>
</html>
Please help how to remove the image from preview and also from pojo variable that being saved to database.
Do empty input file field as well
$(".remove").click(function(){
$(this).parent(".pip").remove();
$("#files").val(null);
});`

JQuery. Facing problems with click events

I was writing code for image flip game in jquery but I am facing some problems with the click events on image in the beginning. The problems are when I click one image and click again the same image it works fine but if I click one image, the image src attribute is added to the img tag and then if I click any other image the src attribute is not added to that one for the first click because the clickCounter has the value 1 then. I employed my own logic (clickCounter). I am new to jquery. You may suggest a better way to do this. Thanks in advance.
Here is my code.
<style>
#main{
height: 500px;
border: 1px solid blue;
margin: auto;
}
.myimg{
width: 100px;
height: 100px;
background: lightblue;
background-position: center center;
margin: 10px;
float: left;
border-radius: 20px;
}
</style>
<body>
<div id="main">
</div>
<button id="add">Add</button>
<script src="jquery-1.11.2.js"></script>
<script>
var clickCounter = 0;
$('#add').click(function(){
addElements(44);
$('#add').attr('disabled', 'true');
});
function addElements(times){
var main = $('#main');
for(j = 1; j <= times; j++){
var i = document.createElement('img');
var img = $(i);
img.click(function(){
// $(this).css('background', 'url(back.png)');
var myImage = $(this);
if(clickCounter == 0){
myImage.attr('src', 'back.png');
myImage.attr('width', '100');
myImage.attr('height', '100');
clickCounter = 1;
}else{
myImage.removeAttr('src');
clickCounter = 0;
}
//alert(clickCounter);
});
img.addClass('myimg');
main.append(img);
}
}
</script>
</body>
JSFiddle
The problem is the shared variable clickCounter which is shared between all the elements.
In this case since you have dynamic elements, you could use event delegation and then use the current src value of the img to set the new one like
$('#add').click(function () {
addElements(44);
$('#add').prop('disabled', true);
});
$('#main').on('click', '.myimg', function () {
$(this).attr('src', function (i, src) {
return src == 'back.png' ? '' : 'back.png';
}).height(100).width(100);
})
function addElements(times) {
var $main = $('#main');
for (j = 1; j <= times; j++) {
$('<img />', {
'class': 'myimg'
}).appendTo($main)
}
}
Demo: Fiddle
Instead of counter, check for 'src' attribute as shown below,
$('#add').click(function(){
addElements(44);
$('#add').attr('disabled', 'true');
});
function addElements(times){
var main = $('#main');
for(j = 1; j <= times; j++){
var i = document.createElement('img');
var img = $(i);
img.click(function(){
// $(this).css('background', 'url(back.png)');
var myImage = $(this);
var attr = $(this).attr('src');
if(typeof attr == typeof undefined){
myImage.attr('src', 'back.png');
myImage.attr('width', '100');
myImage.attr('height', '100');
}else{
myImage.removeAttr('src');
}
//alert(clickCounter);
});
img.addClass('myimg');
main.append(img);
}
}
#main{
height: 500px;
border: 1px solid blue;
margin: auto;
}
.myimg{
width: 100px;
height: 100px;
background: lightblue;
background-position: center center;
margin: 10px;
float: left;
border-radius: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
</div>
<button id="add">Add</button>

Categories

Resources