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>
Related
The program I am creating is a meme generator. I have a div container set up with display:grid with a few tags inside of that which act as the top and bottom text for the meme. I'm trying to dynamically set the background image for the grid cell using plain vanilla JS. When I attach the link inside the CSS file it works perfectly, but using JS the background-image is never set when i check inside the browser. I put a big arrow so you can see where I am attempting to set the image
const imageLink = document.querySelector('#imageLink');
const topText = document.querySelector('#topText');
const bottomText = document.querySelector('#bottomText');
const memeDiv = document.querySelector('#meme');
//listener for submit
document.addEventListener("submit", function(e) {
e.preventDefault();
//if the user doesn't enter an image, or if they don't enter any text, don't generate the meme when they submit.
if (imageLink.value === "") {
return;
} else if (topText === "" && bottomText === "") {
return;
}
console.log(imageLink.value);
//create elements
var div = document.createElement("div");
//set attribute for div containing our memes
div.setAttribute("id", "meme");
//When the page loads apply the users photo to the background of the grid
window.addEventListener('DOMContentLoaded', function() {
memeDiv.style.backgroundImage = `url(${imageLink.value})`; // < -- -- -
});
//create text and remove button for the memes
const top = document.createElement("p"); //for top text
const bottom = document.createElement("p"); //for bottom text
const removeBtn = document.createElement("input");
//remove button attributes
removeBtn.setAttribute("id", "remove");
removeBtn.setAttribute("type", "image");
removeBtn.setAttribute("height", "200px");
removeBtn.setAttribute("width", "200px");
removeBtn.setAttribute(
"src",
"https://www.freeiconspng.com/uploads/x-png-33.png"
);
//set attributes for text
top.setAttribute("id", "top");
top.innerText = topText.value;
bottom.setAttribute("id", "bottom");
bottom.innerText = bottomText.value;
//put the top and bottom text with the remove button together with the same div
div.appendChild(top);
div.appendChild(bottom);
div.appendChild(removeBtn);
//append to the div
document.querySelector("#memeContainer").appendChild(div);
//reset
imageLink.value = "";
topText.value = "";
bottomText.value = "";
})
document.addEventListener("click", function(e) {
if (e.target.id === "remove") {
e.target.parentElement.remove();
} else {
return;
}
})
* {
margin: 0px;
}
#formContainer {
background-color: blue;
margin-bottom: 5px;
text-align: center;
}
h1 {
text-align: center;
background-color: blue;
margin: 0px;
}
#memeContainer {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 300px);
grid-gap: 5px;
}
#top,
#bottom,
#remove {
position: relative;
display: inline;
}
#top {
left: 225px;
z-index: 1;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#bottom {
top: 300px;
left: 225px;
z-index: 2;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#remove {
top: -150px;
left: 180px;
z-index: 3;
/* filter: opacity(1%); */
}
#remove:hover {
z-index: 3;
filter: opacity(25%);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meme Generator</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1>MEME GENERATOR</h1>
<div id="formContainer">
<form>
<input id="imageLink" type="text" placeholder="please link to an image">
<input id="topText" type="text" placeholder="TOP TEXT">
<input id="bottomText" type="text" placeholder="BOTTOM TEXT">
<button type="submit">submit</button>
</form>
</div>
<div id="memeContainer"></div>
<script src="app.js"></script>
</body>
</html>
The DOMContentLoaded event is only called once whenever all HTML have been loaded. So you are only adding an event listener which never fires and thus nothing happens.
window.addEventListener('DOMContentLoaded', function() {
memeDiv.style.backgroundImage = `url(${imageLink.value})`;
});
Remove the event listener and correct the memeDiv variable name to div and your code will run.
div.style.backgroundImage = `url(${imageLink.value})`;
const imageLink = document.querySelector('#imageLink');
const topText = document.querySelector('#topText');
const bottomText = document.querySelector('#bottomText');
const memeDiv = document.querySelector('#meme');
//listener for submit
document.addEventListener("submit", function(e) {
e.preventDefault();
//if the user doesn't enter an image, or if they don't enter any text, don't generate the meme when they submit.
if (imageLink.value === "") {
return;
} else if (topText.value === "" && bottomText.value === "") {
return;
}
console.log(imageLink.value);
//create elements
var div = document.createElement("div");
//set attribute for div containing our memes
div.setAttribute("id", "meme");
//When the page loads apply the users photo to the background of the grid
div.style.backgroundImage = `url(${imageLink.value})`; // < -- -- -
//create text and remove button for the memes
const top = document.createElement("p"); //for top text
const bottom = document.createElement("p"); //for bottom text
const removeBtn = document.createElement("input");
//remove button attributes
removeBtn.setAttribute("id", "remove");
removeBtn.setAttribute("type", "image");
removeBtn.setAttribute("height", "200px");
removeBtn.setAttribute("width", "200px");
removeBtn.setAttribute(
"src",
"https://www.freeiconspng.com/uploads/x-png-33.png"
);
//set attributes for text
top.setAttribute("id", "top");
top.innerText = topText.value;
bottom.setAttribute("id", "bottom");
bottom.innerText = bottomText.value;
//put the top and bottom text with the remove button together with the same div
div.appendChild(top);
div.appendChild(bottom);
div.appendChild(removeBtn);
//append to the div
document.querySelector("#memeContainer").appendChild(div);
//reset
imageLink.value = "";
topText.value = "";
bottomText.value = "";
})
document.addEventListener("click", function(e) {
if (e.target.id === "remove") {
e.target.parentElement.remove();
} else {
return;
}
})
* {
margin: 0px;
}
#formContainer {
background-color: blue;
margin-bottom: 5px;
text-align: center;
}
h1 {
text-align: center;
background-color: blue;
margin: 0px;
}
#memeContainer {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 300px);
grid-gap: 5px;
}
#top,
#bottom,
#remove {
position: relative;
display: inline;
}
#top {
left: 225px;
z-index: 1;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#bottom {
top: 300px;
left: 225px;
z-index: 2;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#remove {
top: -150px;
left: 180px;
z-index: 3;
/* filter: opacity(1%); */
}
#remove:hover {
z-index: 3;
filter: opacity(25%);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meme Generator</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1>MEME GENERATOR</h1>
<div id="formContainer">
<form>
<input id="imageLink" type="text" placeholder="please link to an image">
<input id="topText" type="text" placeholder="TOP TEXT">
<input id="bottomText" type="text" placeholder="BOTTOM TEXT">
<button type="submit">submit</button>
</form>
</div>
<div id="memeContainer"></div>
<script src="app.js"></script>
</body>
</html>
I'm new to Cordova, and I'm trying to build an android app
I copied my files into www file and replaced its files with mine
and build apk but when running it on my phone the first two buttons only are working (Equal weight / Unequal weight) while the (add more/ reset/ result buttons ) are not, but when I'm trying to check my code as a web page it works perfectly, as you might see in the snippet
I also tried to keep the cordova.js file and the index.js with my app.js but it didn't work
I tried to add cordova.js and index.js (the files that created automatically when creating a project with Cordova) but it didn't work
//declare the main buttons and divs
const btn1 = document.querySelector('.eqbtn'),
btn2 = document.querySelector('.uneqbtn'),
div1 = document.querySelector('.eqdiv'),
div2 = document.querySelector('.wrap-sub')
div_2 = document.querySelector('.uneqdiv');
//add event listeners to the main buttons
btn1.addEventListener('click', equalFunc);
btn2.addEventListener('click', unequalFunc);
//switch between two keys
function equalFunc() {
togFunc(div1, div_2, btn1, btn2);
resetFunc('.eqdiv', div1);
}
function unequalFunc() {
togFunc(div_2, div1, btn2, btn1);
resetFunc('.wrap-sub', div2);
}
function togFunc(one, two, a, b) {
a.classList.add('active');
b.classList.remove('active');
one.style.display = 'block';
two.style.display = 'none';
}
//declare the equal addmore button
const btnplus = document.querySelector('.eqmore');
const unbtnplus = document.querySelector('.un-eqmore');
//fire when addmore button get fired
btnplus.addEventListener('click', () => {
if (checkIn('.eqdiv') === false) {
errIn();
} else {
creatIn(div1);
}
});
//fire when uneqaddmore get clicked
unbtnplus.addEventListener('click', () => {
if (checkIn('.wrap-sub') === false) {
errIn();
} else {
creatIn(div2);
}
})
//check the value of the inputs
function checkIn(nav) {
let bool;
document.querySelectorAll(`${nav} input`).forEach((elem) => {
if (elem.value === '' || elem.value < 0) {
elem.style.borderColor = '#f86868';
bool = false;
} else {
elem.style.borderColor = '#D1D1D1';
}
});
return bool;
}
//create the input and assign it's value
function creatIn(dnav) {
if (dnav === div1) {
const dive = document.createElement('div');
dive.innerHTML = `<input type ='number'/>`;
dnav.insertBefore(dive, btnplus);
} else {
const sp1 = document.createElement('div'),
sp2 = document.createElement('div');
sp1.innerHTML = `<input type ='number'>`;
sp2.innerHTML = `<input type ='number'>`;
document.querySelector('.div2-1').appendChild(sp2);
document.querySelector('.div2-2').appendChild(sp1);
}
}
//fire an error if the user insert wrong value
function errIn() {
const errdiv = document.createElement('div');
errdiv.innerHTML = `Please fill inputs with positive values`;
errdiv.classList.add('errdiv');
document.querySelector('.wrap').insertAdjacentElement('beforeend', errdiv);
setTimeout(() => errdiv.remove(), 1800);
}
//fire when the reset button get clicked
function resetFunc(x, y) {
document.querySelectorAll(`${x} input`).forEach(reset => {
reset.remove();
});
document.querySelector('#output').innerHTML = '';
creatIn(y);
}
//reset all the inputs
document.querySelector('.reset').addEventListener('click', () => resetFunc('.eqdiv', div1));
document.querySelector('.un-reset').addEventListener('click', () => resetFunc('.wrap-sub', div2));
//fire when result button get fired
document.querySelector('.result').addEventListener('click', resFunc);
document.querySelector('.un-result').addEventListener('click', unresFunc);
//declare result function when result button get clicked
function resFunc() {
if (checkIn('.eqdiv') === false) {
errIn();
} else {
let arr = [];
document.querySelectorAll('.eqdiv input').forEach(res => arr.push(Number(res.value)));
const num = arr.length;
const newarr = arr.reduce((a, b) => a + b);
const mean = newarr / num;
const resarr = [];
arr.forEach(re => resarr.push((re - mean) * (re - mean)));
const newresarr = resarr.reduce((c, v) => c + v);
const norDev = Math.sqrt(newresarr / (num - 1));
const dev = norDev / Math.sqrt(num);
let mpv;
if (!isNaN(dev)) {
mpv = `${mean.toFixed(3)} ± ${dev.toFixed(3)}`;
} else {
mpv = `${mean.toFixed(3)}`;
}
displayResult(mpv);
}
}
function unresFunc() {
if (checkIn('.wrap-sub') === false) {
errIn();
} else {
let allweight = [],
allValues = [],
subMeanArray = [],
sub = [],
semiFinal = [];
document.querySelectorAll('.div2-2 input').forEach(w => allweight.push(Number(w.value)));
const sumWeight = allweight.reduce((n, m) => n + m);
document.querySelectorAll('.div2-1 input').forEach(s => allValues.push(Number(s.value)));
for (i = 0; i < allweight.length; i++) {
subMeanArray.push(allweight[i] * allValues[i]);
}
const sumMean = subMeanArray.reduce((a, b) => a + b);
const mean = sumMean / sumWeight;
allValues.forEach(s => sub.push(s - mean));
for (i = 0; i < allweight.length; i++) {
semiFinal.push(allweight[i] * sub[i] * sub[i]);
}
const alFinal = semiFinal.reduce((a, b) => a + b);
const nDev = Math.sqrt(alFinal / allweight.length);
const Dev = nDev / Math.sqrt(sumWeight);
let mpv;
if (isNaN(Dev)) {
mpv = ` : No choice but the only value you gave which is ${allValues[0].toFixed(3)}`;
} else {
mpv = `${mean.toFixed(3)} ± ${Dev.toFixed(3)}`;
}
displayResult(mpv);
}
}
function displayResult(wow) {
document.querySelector('#output').innerHTML = `The Result is ${wow}`;
}
.wrap>div {
display: none;
}
/* .uneqdiv{
display: none;
} */
.container {
padding-top: 100px;
width: max-content;
padding-bottom: 50px;
}
.wrap {
margin-top: 50px;
}
.wrap-sub {
display: flex;
}
.div2-1 {
margin-right: 5px;
}
button {
outline: none;
transition: border .3s;
}
.active,
.active:focus {
border-color: #46d84d;
}
button.reset:hover,
button.un-reset:hover {
border-color: #f86868;
}
button.eqmore:hover,
button.un-eqmore:hover {
border-color: #46d84d;
}
.errdiv {
height: 40px;
width: 100%;
background-color: #df4f4f;
color: #ffffff;
display: flex !important;
justify-content: center;
align-items: center;
}
#output {
padding-top: 20px;
}
h6 {
margin: 0;
}
.tes {
display: inline-block;
}
#media(max-width: 700px) {
.container {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.container>h2 {
font-size: 2rem;
}
button {
width: 75%;
max-width: 20rem;
}
.wrap {
display: flex;
flex-direction: column;
align-items: center;
width: 90%;
}
.eqdiv {
text-align: center;
}
.eqdiv input {
max-width: 20rem;
width: 75%;
}
.eqdiv button {
display: block;
margin-left: auto;
margin-right: auto;
}
.uneqdiv {
text-align: center;
width: 100%;
}
.wrap-sub input {
max-width: 25rem;
width: 100%;
}
.uneqdiv .wrap-sub {
width: 100%;
margin-top: 40px;
margin-bottom: 15px;
display: flex;
flex-direction: column;
align-items: center;
}
.wrap-sub h6 {
font-size: 1.4rem;
}
.tes button {
width: 100%;
}
}
<html>
<head>
<meta content="utf-8">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/skeleton.css">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>survey</title>
</head>
<body>
<div class="container">
<h2 class="jui">Please select the wanted method</h2>
<button class="eqbtn">equal weight</button>
<button class="uneqbtn">unequal weight</button>
<div class="wrap">
<div class="eqdiv">
<h4>Enter the equal values</h4>
<div>
<input type="number" class="init">
</div>
<button class="eqmore">add more +</button>
<button class="reset">reset</button>
<button class="result button-primary">result</button>
</div>
<div class="uneqdiv">
<h4>Enter the unequal values</h4>
<div class="wrap-sub">
<div class="div2-1">
<h6>The Measurements</h6>
<input type="number" class="un-init">
</div>
<div class="div2-2">
<h6>The Weights</h6>
<input type="number" class="un-weight">
</div>
</div>
<div class="tes">
<button class="un-eqmore">add more +</button>
<button class="un-reset">reset</button>
<button class="un-result button-primary">result</button>
</div>
</div>
</div>
<div id="output"></div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
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);
});`
I don't know how to describe this without making it more complicated.
So look at the result of the code and click on the first link with "Show", then the second one and third one.
When the second link is clicked, first one closes but text remains "Hide" and i want it to change to "Show".
So, when clicking a link, detect if any other link has text "Hide" and change it to "Show".
And please no jQuery...
document.getElementsByClassName("show")[0].onclick = function() {
var x = document.getElementsByClassName("hide")[0];
var y = document.getElementsByClassName("show")[0];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[1].onclick = function() {
var x = document.getElementsByClassName("hide")[1];
var y = document.getElementsByClassName("show")[1];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[2].onclick = function() {
var x = document.getElementsByClassName("hide")[2];
var y = document.getElementsByClassName("show")[2];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
function closeOther() {
var visible = document.querySelectorAll(".visible"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].classList.remove("visible");
}
}
.style {
background-color: yellow;
width: 200px;
height: 200px;
display: inline-block;
}
.hide {
background-color: red;
width: 50px;
height: 50px;
display: none;
position: relative;
top: 50px;
left: 50px;
}
.hide.visible {
display: block;
}
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
I tried to write a solution which didn't use any javascript at all and worked using CSS alone. I couldn't get it to work though - CSS can identify focus but it can't identify blur (ie. when focus has just been removed).
So here is a solution which uses javascript and the classList API, instead:
var divs = document.getElementsByTagName('div');
function toggleFocus() {
for (var i = 0; i < divs.length; i++) {
if (divs[i] === this) continue;
divs[i].classList.add('show');
divs[i].classList.remove('hide');
}
this.classList.toggle('show');
this.classList.toggle('hide');
}
for (let i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', toggleFocus, false);
}
div {
display: inline-block;
position: relative;
width: 140px;
height: 140px;
background-color: rgb(255,255,0);
}
.show::before {
content: 'show';
}
.hide::before {
content: 'hide';
}
div::before {
color: rgb(0,0,255);
text-decoration: underline;
cursor: pointer;
}
.hide::after {
content: '';
position: absolute;
top: 40px;
left: 40px;
width: 50px;
height: 50px;
background-color: rgb(255,0,0);
}
<div class="show"></div>
<div class="show"></div>
<div class="show"></div>
Like this?
Just added following to closeOther():
visible = document.querySelectorAll(".show"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].textContent="Show";
}
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("");
});`