How can i select multiple pictures using change event? - javascript

How can i select multiple pictures. right now i'm able to get pictures single-single but i want to get multiple. how can i do that?
What i tried:-
$(function() {
$(document).on('change', '.caFileBtn', function() {
console.log(imagePath);
var files = this.files
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imagePath = URL.createObjectURL(file);
}
var imageElement = `
<div>
<img src="${imagePath}" />
</div>
`;
$('.ca-photos-area').show();
$('.ca-photos-area').prepend(imageElement);
$(this).val('');
});
});
.ca-photos-area {
display: flex;
}
.ca-photos-area img {
width: 90px;
height: 90px;
margin: 5px;
border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="btn btn-primary btn-block">
<input type="file" Multiple="Multiple" class="caFileBtn" />
<i class="fas fa-image"></i>
</div>
<div class="col-md-12">
<div class="ca-photos-area mt-3">
</div>
</div>
Answer will be appreciated

While html tags and attributes are case-insensitive it's best practice to use lowercase. Though, attribute values are case-sensitive. So, you must define multiple in lowercase:
<input type="file" multiple="multiple" class="caFileBtn" />
<!-- Must be in lowercase --- ^^ -->
<!-- Otherwise, it's still single type -->
Or, you could also have defined attribute only:
<input type="file" multiple class="caFileBtn" />
The above answer seems to be wrong in the case of multiple attribute as it accepts boolean and using it case-insensitive also meant to be multiple.
Here's the working javascript code that will select all selected images:
$(function() {
$(document).on('change', '.caFileBtn', function() {
console.log(imagePath);
var files = this.files
var imageElement = [];
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imagePath = URL.createObjectURL(file);
imageElement.push( `
<div>
<img src="${imagePath}" />
</div>`);
}
for (var i=0; i<imageElement.length; i++){
$('.ca-photos-area').prepend(imageElement[i]);
}
$('.ca-photos-area').show();
$(this).val('');
});
});

Issue
The majority of the statements within handler were outside the for loop. BTW I removed the reset statement: $(this).val('') because the tag would always display: "no files selected..." whether there were files selected or not. Without the reset you get a list of the file names selected.
Demo
$('.caFileBtn').on('change', function() {
const self = $(this)[0];
const files = self.files;
let imagePath, imageTag;
for (let i = 0; i < files.length; i++) {
let file = files[i];
imagePath = URL.createObjectURL(file);
imageTag = `<figure><img src="${imagePath}"></figure>`;
$('.ca-photos-area').prepend(imageTag);
}
});
.ca-photos-area {
display: flex;
}
.ca-photos-area img {
width: 90px;
height: 90px;
margin: 5px;
border: 1px solid #ccc;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" rel="stylesheet" crossorigin="anonymous">
<label class="btn btn-primary btn-block">
<input class="caFileBtn" type="file" multiple="multiple">
<i class="fas fa-image"></i>
</label>
<section class="col-md-12">
<article class="ca-photos-area mt-3"></article>
</section>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>

Related

add hyperlink with images by button or Drag and save current state [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
<style>
.grid {
display: flex;
flex-wrap: wrap;
}
.grid-item {
width: 50%;
}
#media (max-width: 600px) {
.grid-item {
width: 100%;
}
}
img {
width: 100%;
}
a {
display: block;
text-align: center;
}
input[type="text"] {
width: 100%;
}
</style>
<div class="grid">
<div class="grid-item"><img src="image1.jpg" /></div>
<div class="grid-item"><img src="image2.jpg" /></div>
<div class="grid-item"><img src="image3.jpg" /></div>
<div class="grid-item"><img src="image4.jpg" /></div>
</div>
<form>
<input type="text" placeholder="Enter image URL" />
<input type="text" placeholder="Enter hyperlink URL" />
<button type="submit">Add item</button>
</form>
<script>
var grid = document.querySelector('.grid');
var gridItems = document.querySelectorAll('.grid-item');
var form = document.querySelector('form');
// Load the saved grid state from local storage
var gridState = JSON.parse(localStorage.getItem('gridState'));
if (gridState) {
for (var i = 0; i < gridState.length; i++) {
var gridItem = document.createElement('div');
gridItem.classList.add('grid-item');
gridItem.innerHTML = '<img src="' + gridState[i].imageUrl + '" />';
grid.appendChild(gridItem);
}
}
for (var i = 0; i < gridItems.length; i++) {
gridItems[i].addEventListener('click', function(event) {
window.location.href = this.querySelector('a').getAttribute('href');
});
}
form.addEventListener
('submit', function(event) {
event.preventDefault();
var imageUrl = this.querySelector('input[type="text"]').value;
var hyperlinkUrl = this.querySelector('input[type="text"]').value;
var gridItem = document.createElement('div');
gridItem.classList.add('grid-item');
gridItem.innerHTML = '<img src="' + imageUrl + '" />';
grid.appendChild(gridItem);
// Save the grid state to local storage
var gridState = [];
for (var i = 0; i < gridItems.length; i++) {
var imageUrl = gridItems[i].querySelector('img').getAttribute('src');
var hyperlinkUrl = gridItems[i].querySelector('a').getAttribute('href');
gridState.push({
imageUrl: imageUrl,
hyperlinkUrl: hyperlinkUrl
});
}
localStorage.setItem('gridState', JSON.stringify(gridState));
});
</script>
1.This is the full code I don't know why It isn't functional
2. Is there alternative way to save and change code itself? rather than use local storage?
I want functional code
Please help me, I am wandering for more than 24hours now
I suppose you want to take two inputs image's source link and the hyper link it redirects to and store these inputted values and get them when user visits site again.
1. You code was fine just that you were not getting values from those input fields. You can change.
var imageUrl = this.querySelector('input[type="text"]').value;
var hyperlinkUrl = this.querySelector('input[type="text"]').value;
to this (and add respective ids in their input tags)
var imageUrl = document.getElementById('image_url').value;
var hyperlinkUrl = document.getElementById('link').value;
<input id="image_url" type="text" placeholder="Enter image URL" />
<input id="link" type="text" placeholder="Enter hyperlink URL" />
See this my version of code here: https://jsfiddle.net/gktazfjw/
var grid = document.querySelector('.grid');
var gridItems = document.querySelectorAll('.grid-item');
var form = document.querySelector('form');
var tempLink = "https://robohash.org/"
// Load the saved grid state from local storage
var gridState = JSON.parse(localStorage.getItem('gridState'));
if (gridState) {
for (var i = 0; i < gridState.length; i++) {
var gridItem = document.createElement('div');
gridItem.classList.add('grid-item');
gridItem.innerHTML = '<a target="_blank" href="' + gridState[i].hyperlinkUrl + '"><img src="' + gridState[i].imageUrl + '" /></a>';
grid.appendChild(gridItem);
}
}
for (var i = 0; i < gridItems.length; i++) {
gridItems[i].addEventListener('click', function(event) {
window.location.href = this.querySelector('a').getAttribute('href');
});
}
form.addEventListener('submit', function(event) {
event.preventDefault();
var imageUrl = document.getElementById('image_url').value;
var hyperlinkUrl = document.getElementById('link').value;
alert(imageUrl + ": " + hyperlinkUrl)
var gridItem = document.createElement('div');
gridItem.classList.add('grid-item');
gridItem.innerHTML = '<img src="' + tempLink + imageUrl + '" />';
grid.appendChild(gridItem);
// Save the grid state to local storage
var gridState = [];
for (var i = 0; i < gridItems.length; i++) {
var imageUrl = gridItems[i].querySelector('img').getAttribute('src');
var hyperlinkUrl = gridItems[i].querySelector('a').getAttribute('href');
gridState.push({
imageUrl: imageUrl,
hyperlinkUrl: hyperlinkUrl
});
}
localStorage.setItem('gridState', JSON.stringify(gridState));
});
.grid {
display: flex;
flex-wrap: wrap;
}
.grid-item {
width: 50%;
}
#media (max-width: 600px) {
.grid-item {
width: 100%;
}
}
img {
width: 30%;
}
a {
display: block;
text-align: center;
}
input[type="text"] {
width: 100%;
}
<div class="grid">
<div target="_blank" class="grid-item">
<a href="https://example.com">
<img src="https://robohash.org/image1" />
</a>
</div>
<div target="_blank" class="grid-item">
<a href="https://example.com">
<img src="https://robohash.org/image2" />
</a>
</div>
<div target="_blank" class="grid-item">
<a href="https://example.com">
<img src="https://robohash.org/image3" />
</a>
</div>
<div target="_blank" class="grid-item">
<a href="https://example.com">
<img src="https://robohash.org/image4" />
</a>
</div>
</div>
<form>
<input id="image_url" type="text" placeholder="Enter image URL" />
<input id="link" type="text" placeholder="Enter hyperlink URL" />
<button type="submit">Add item</button>
</form>
2. Much better way is to store data in some kind of free cloud database like mongoDB, firebase, etc.
Local storage can be cleared by the user and is limited by the amount of data we can store, but is perfectly fine if it's just for practice , etc and you don't want to use your project for professional things.
But the thing is if you start using some database with your website then you will have to implement authentication logic too, to get only the desired data of any user.
var imageUrl = this.querySelector('input[type="text"]').value;
var hyperlinkUrl = this.querySelector('input[type="text"]').value
You can simply add it by using this code

how to add Add products on shopping cart without js framework

I am Beginner developer and I made e-commerce website (using html css and JavaScript(without framework)
I stuck in Add products on shopping cart because JavaScript and these my Code:
HTML:
<div class="small-container">
<div class="row">
<div class="col-4">
<img src="images/20 ps4.png" alt=""/></a>
<h4>20 Playstation Store(PSN)</h4>
<p>$20.00</p>
<button type="button" class="btn1" ><h3 class="text-btn">add to cart</h3></button>
</div>
<!--2-->
<div class="col-4">
<img src="images/25 ps4.png" alt="" />
<h4>25 Playstation Store(PSN)</h4>
<p>$25.00</p>
<button type="button" class="btn1" onclick="window.location.href='cart.html'"><h3 class="text-btn">add to cart</h3></button>
</div>
JavaScript:
function ready() {
var removeCartItemButtons = document.getElementsByClassName('btn1')
for (var i = 0; i < removeCartItemButtons.length; i++) {
var button = removeCartItemButtons[i]
button.addEventListener('click', removeCartItem)
}
var quantityInputs = document.getElementsByClassName('btn1')
for (var i = 0; i < quantityInputs.length; i++) {
var input = quantityInputs[i]
input.addEventListener('change', quantityChanged)
}
var addToCartButtons = document.getElementsByClassName('btn1')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
document.getElementsByClassName('btn1')[0].addEventListener('click', purchaseClicked)
}
Css :
.row {
margin-top: 50px;
display: flex;
align-items: center;
flex-wrap: wrap;
justify-content: space-around;
}
.small-container{
max-width: 1080px;
margin: auto;
padding-left: 25px;
padding-right: 25px;
}
.col-4 {
flex-basis: 25%;
padding: 10px;
min-width: 200px;
margin-bottom: 50px;
transition: transform 0.5s;
}
.col-4 img {
width: 100%;
}
Thanks a lot.
I try to find function to add products item to the shopping cart
also i have to use JavaScript without framework
What's the purpose of var addToCartButtons = document.getElementsByClassName('btn1'), var quantityInputs = document.getElementsByClassName('btn1') and var removeCartItemButtons = document.getElementsByClassName('btn1')? The query is the same and therefore will always return identical elements.
Your approach is good, just add correct classes to your elements and queries. Be sure to make the HTML structure uniform. Metadata about your card can be stored in localStorage for example. You can learn about working with localStorage here. By the way, you can use newer syntax like forof loops or const keyword to make your code more readable.
(() => {
const addToCardButtons = document.querySelectorAll('.btn--add_to_cart');
for (const btn of addToCardButtons) {
const identifier = btn.dataset.target;
btn.addEventListener('click', () => addToCart(identifier))
}
const addToCart = (id) => {
console.log(id);
// handle 'add to cart' functionality
}
// other functionalities can follow the same structure
})()
<div class="small-container">
<div class="row">
<div class="col-4">
<img src="images/20 ps4.png" alt="" /></a>
<h4>20 Playstation Store(PSN)</h4>
<p>$20.00</p>
<button type="button" data-target="1" class="btn btn--add_to_cart">add to cart</button>
</div>
<!--2-->
<div class="col-4">
<img src="images/25 ps4.png" alt="" />
<h4>25 Playstation Store(PSN)</h4>
<p>$25.00</p>
<button type="button" data-target="2" class="btn btn--add_to_cart">add to cart</button>
</div>

How to include a input in a label in a querySelector() in javascript?

I am trying to construct a personality quiz for my school project. Everything was working fine until I decided that I want the inputs for the radio buttons to be just pictures. The problem is that I am not sure how to save the selected choice and its value, in order to calculate the result.
This is my HTML code:
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<input type="radio" name="colour" class="a" value="-1" />
<label for="p">
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
This is my CSS:
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
And this is my Javascript:
function submitSimpleQuiz() {
"use strict";
var colour = praseInt(document.querySelector('input[name = "colour"]:checked').value);
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
} else {
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
This is just one question and answer but essentially all the answers should add up to an outcome which will display a personality description. I don't know why the button for submitting doesn't work anymore.
I would greatly appreciate the help.
I am only new to coding, but I tried including the label into the javascript and also changing the layout of the HTML so that the input is included in the label tag.
As I am sure you won't stop with only 1 question, here is a working snippet in which you can add more questions easily:
function submitSimpleQuiz() {
"use strict";
var total = 0;
var answer = ""; // Added, just because… (see below)
// Easy selection, now! That counts only "selected" inputs!
var inputs = document.querySelectorAll("#simplequiz .selected input");
for (var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if (total < 0) {
answer = "Goth";
} else {
answer = "Minimalistic";
}
// Moved outside of the if to only have these instructions one time
document.getElementById("simplequiz").style.display = "none";
document.getElementById("answer").innerHTML = answer;
}
// Your other code, I haven't touched it. Promise.
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<!-- Modified order -->
<label for="p">
<input type="radio" name="colour" class="a" value="-1" />
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
<!-- Added another one below -->
<label for="p">
<input type="radio" name="colour" class="a" value="1" />
<img src="images/2.jpg" alt="Minimal colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
<!-- Added "answer" -->
<div id="answer"></div>
Anyway, I've got a few remarks, here:
⋅ Your function submitSimpleQuiz is in JavaScript only, whereas your other code is in jQuery. You should choose what you want to use!
⋅ I moved the inputs in your labels to make it easier to select them.
⋅ Why are you using inputs if you're hiding them, and can't/don't check them?!…
Hope it helps.
You need to remove line :
$('#simplequiz input:radio').addClass('input_hidden');
Or you need to modify the line:
var colour = parseInt(document.querySelector('input[name = "colour"]:checked').value);
Because if you uncheck radiobutton you can't get the value. And You have to use parseInt not praseInt. it's an error.
First off all you need to import Jquery for using Jquery function $.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Second it is parseInt not praseInt.
Third:
use this piece of code instead of yours:
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
Fourth:
for your script to work correctly your javasScript should be -
<script type="text/javascript">
function submitSimpleQuiz(){
"use strict";
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
if (document.querySelector("div#simplequiz input[name = 'colour']").checked) {
colour = 0;
}
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
}
else
{
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>

Uploadcare with multiple previews and more than one instance

How do I change the script to also populate the src of the images contained in .seperate-group, matching the uploaded images in A with FOR A and B with FOR B?
var $ = uploadcare.jQuery;
var widgets = uploadcare.initialize(); // get all widget instances
widgets.forEach(function(widget) {
widget.onUploadComplete(function(fileInfo) {
var group = $(widget.inputElement).closest(".group"); // find a group the instance is related to
$(group).find('.feature-img').each(function(i, img) { // find image tags in the group
img.src = fileInfo.cdnUrl; // update previews
});
});
});
.image-input {
display: block;
position: relative;
height: 100px;
width: 200px;
}
.container {
display: flex;
}
.image-preview-wrapper {
height: 50px;
}
.feature-img {
height: 100%;
}
.seperate-group img {
height: 100px;
width: 100px;
}
<div class="container">
<div class="group">A
<div class="image-input">
<input type="hidden" role="uploadcare-uploader" data-clearable="" data-images-only="" data-public-key="1c86ca998ba22e75fbc6" value="">
</div>
<div class="image-preview-wrapper">
<img class="feature-img" src="http://www.pixedelic.com/themes/geode/demo/wp-content/uploads/sites/4/2014/04/placeholder4.png"></img>
<img class="feature-img" src="http://www.pixedelic.com/themes/geode/demo/wp-content/uploads/sites/4/2014/04/placeholder4.png"></img>
</div>
</div>
<div class="group">B
<div class="image-input">
<input type="hidden" role="uploadcare-uploader" data-clearable="" data-images-only="" data-public-key="1c86ca998ba22e75fbc6" value="">
</div>
<div class="image-preview-wrapper">
<img class="feature-img" src="http://www.pixedelic.com/themes/geode/demo/wp-content/uploads/sites/4/2014/04/placeholder4.png"></img>
<img class="feature-img" src="http://www.pixedelic.com/themes/geode/demo/wp-content/uploads/sites/4/2014/04/placeholder4.png"></img>
</div>
</div>
<div class="seperate-group">
<img class="feature-img" src="http://www.pixedelic.com/themes/geode/demo/wp-content/uploads/sites/4/2014/04/placeholder4.png">FOR A</img>
<img class="feature-img" src="http://www.pixedelic.com/themes/geode/demo/wp-content/uploads/sites/4/2014/04/placeholder4.png">FOR B</img>
</div>
</div>
<script>
UPLOADCARE_LOCALE = "en";
UPLOADCARE_TABS = "file url facebook dropbox instagram";
UPLOADCARE_PUBLIC_KEY = "7d504e167ecaef7b82d4";
</script>
<script charset="utf-8" src="//ucarecdn.com/libs/widget/3.2.2/uploadcare.full.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Kyle, try this code snippet
var $ = uploadcare.jQuery;
var widgets = uploadcare.initialize(); // get all widget instances
widgets.forEach(function (widget) {
widget.onUploadComplete(function (fileInfo) {
var group = $(widget.inputElement).parent().parent(); // find a group the instance is related to
$(group).find('.feature-img').each(function (i, img) { // find image tags in the group
img.src = fileInfo.cdnUrl; // update previews
});
});
});

upload with multiple image preview

I am using this source: http://opoloo.github.io/jquery_upload_preview/
until now, I can upload one image with preview.
<style type="text/css">
.image-preview {
width: 200px;
height: 200px;
position: relative;
overflow: hidden;
background-color: #000000;
color: #ecf0f1;
}
input[type="file"] {
line-height: 200px;
font-size: 200px;
position: absolute;
opacity: 0;
z-index: 10;
}
label {
position: absolute;
z-index: 5;
opacity: 0.7;
cursor: pointer;
background-color: #bdc3c7;
width: 200px;
height: 50px;
font-size: 20px;
line-height: 50px;
text-transform: uppercase;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
text-align: center;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("image-preview").each(
function(){
$.uploadPreview({
input_field: $(this).find(".image-upload"),
preview_box: this,
label_field: $(this).find(".image-label")
});
}
);
});
</script>
<!--| catatan penting: yang penting action="" & input type="file" name="image" |-->
<form action="upload.php" method="POST" enctype="multipart/form-data">
<div class="image-preview">
<label for="image-upload" class="image-label">+ GAMBAR</label>
<input type="file" name="my_field[]" class="image-upload" />
</div>
<div class="image-preview">
<label for="image-upload" class="image-label">+ GAMBAR</label>
<input type="file" name="my_field[]" class="image-upload" />
</div>
<input type="submit"/>
</form>
then try to add more div class image preview, i want add another button with image preview. i don't want multiple upload with one button.
$(document).ready(function() {$.uploadPreview => use id, of course when change to class and add more div, when upload a button, another button will change. i am confused with the logic. Anyone can help? maybe using array but, i don't know how..
Since upload button is dependent on state of uploadPreview you need to initialize for each div separately to get separate upload buttons.
Change your html like this give each container a class say imgBox
<div class="imgBox">
<label for="image-upload" class="image-label">Choose File</label>
<input type="file" name="image" class="image-upload" />
</div>
.....
....
...
<div class="imgBox">
<label for="image-upload" class="image-label">Choose File</label>
<input type="file" name="image" class="image-upload" />
</div>
..
Now initialize each one using jquery each()
$(".imgBox").each(
function(){
$.uploadPreview({
input_field: $(this).find(".image-upload"),
preview_box: this,
label_field: $(this).find(".image-label")
});
});
I created a simple image uploading index.html file for image uploading and preview.
Needs j-query.No need of extra plugins.
If you have any questions ask me ;)
//to preview image you need only these lines of code
var imageId=idOfClicked;
var output = document.getElementById(imageId);
output.src = URL.createObjectURL(event.target.files[0]);
Check it here:
https://jsfiddle.net/chs3s0jk/6/
I have one better option for the file upload it's easy to use and you can try it.
window.onload = function(){
if(window.File && window.FileList && window.FileReader){
$(document).on("change",'.file', function(event) {
var files = event.target.files; //FileList object
var output = document.getElementById("upload-preview");
$("#upload-preview").html("");
if(files.length>5){
$(".file").after("<div class='alert alert-error'><span class='close'></span>Maximum 5 files can be uploaded.</div>");
$(this).val("");
return false;
}
else{
$(".file").next(".alert").remove();
}
for(var i = 0; i< files.length; i++)
{
var file = files[i];
//Only pics
// if(!file.type.match('image'))
if(file.type.match('image.*')){
if(this.files[0].size < 2097152){
// continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var div = document.createElement("div");
div.className = "upload-preview-thumb";
div.style.backgroundImage = 'url('+picFile.result+')';
output.insertBefore(div,null);
});
//Read the image
$('#clear, #upload-preview').show();
picReader.readAsDataURL(file);
}else{
alert("Image Size is too big. Minimum size is 1MB.");
$(this).val("");
}
}else{
alert("You can only upload image file.");
$(this).val("");
}
}
});
$(".file2").change(function(event){
var err=0;
var input = $(event.currentTarget);
var ele = $(this);
var file = input[0].files[0];
var u = URL.createObjectURL(this.files[0]);
var w = ele.attr("data-width");
var h = ele.attr("data-height");
var img = new Image;
img.onload = function(){
if(w){
if(img.width!=w || img.height!=h){
ele.parent().find(".alert").remove();
ele.parent().find(".upload-preview").before("<div class='alert alert-error'>Please upload a image with specified dimensions.</div>");
ele.val("");
}
else{
ele.parent().find(".alert").remove();
}
}
};
img.src = u;
var nh;
if($(this).attr('data-preview')=='full')
nh = (h/w*150)
else
nh=150
var preview = ele.parent().find(".upload-preview");
var reader = new FileReader();
preview.show();
reader.onload = function(e){
image_base64 = e.target.result;
preview.html("<div class='upload-preview-thumb' style='height:"+nh+"px;background-image:url("+image_base64+")'/><div>");
};
reader.readAsDataURL(file);
});
}
else
{
console.log("Your browser does not support File API");
}
}
above code save as one js file like file-upload.js
then link it to your file where you want perview.
i.e.
<script src="js/file-upload.js" type="text/javascript"></script>
use this kind of example for the input type
<input type="file" class="file2" name="page-image" id="page-image"/>
that works on the class that name is "file2" that class you given to the input field that able to create preview.
full structure something like below.
HTML Code you can try
<input type="file" class="file2" name="page-image[]" id="page-image"/>
<div class="clearfix"></div>
<div class="upload-preview" style="display: block;">
<div class="upload-preview-thumb">
// perview genereate here
// you can display image also here if uploaded throw the php condition in edit image part
</div>
</div>
<input type="file" class="file2" name="page-image[]" id="page-image"/>
<div class="clearfix"></div>
<div class="upload-preview" style="display: block;">
<div class="upload-preview-thumb">
// perview genereate here
// you can display image also here if uploaded throw the php condition in edit image part
</div>
</div>
CSS
.upload-preview {
border: 1px dashed #ccc;
display: block;
float: left;
margin-top: 10px;
padding: 5px;
}
.upload-preview-thumb {
background-position: 50% 25%;
background-size: cover;
float: left;
margin: 5px;
position: relative;
width: 139px;
}
Hope this works and in future it's helpful for you.
Thanks.

Categories