Making script re-useable, i.e not keep repeating it? - javascript

Is there a better way of doing this in js? Or more so, how would I do this better in js?
So I don't have 3 scripts basically the same.
Thank you for any help in advance
<label for="img1">Image 1:</label>
<input type="file" id="img1" name="img1" />
<img id="image1"/>
<script>
document.getElementById("img1").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image1").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
</script>
<label for="img2" >Image 2:</label>
<input type="file" id="img2" name="img2" />
<img id="image2"/>
<script>
document.getElementById("img2").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image2").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
</script>
<label for="img3">Image 3:</label>
<input type="file" id="img3" name="img3" />
<img id="image3"/>
<script>
document.getElementById("img3").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image3").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
</script>
Trying to explain myself a little better.
For example in python, loop through something and use the i in the function.
gg = ("a", "q", "f", "4", "f", "h")
for i in range(len(gg)):
print ('thing'+str(i))

<label for="img1">Image 1:</label>
<input type="file" id="img1" name="img1" />
<img id="image1"/>
<label for="main_img">Image 2:</label>
<input type="file" id="img2" name="img2" />
<img id="image2"/>
<label for="main_img">Image 3:</label>
<input type="file" id="img3" name="img3" />
<img id="image3"/>
<script>
imgOnChange('img1','image1');
imgOnChange('img2','image2');
imgOnChange('img3','image3');
function imgOnChange(imgId, imageId) {
document.getElementById(imgId).onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById(imageId).src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
}
</script>

Related

how to preview images in multiple input type "file"-s

I have this code:
const chosenImage = document.getElementById('chosen_image')
for (const input of document.querySelectorAll('input[type=file]')) {
input.onchange = (e) => {
if (e.target.files.length) {
let reader = new FileReader();
console.log(e.target.nextElementSibling);
// do stuff
reader.readAsDataURL(input.files[0]);
reader.onload = () => {
chosenImage.setAttribute("src", reader.result);
e.target.nextElementSibling.textContent = e.target.nextElementSibling.textContent.replace(/False/, input.files[0].name)
}
}
}
}
<div class="section_header">
<figure class="uploaded_image_container">
<img id="chosen_image">
</figure>
<div class="upload_section_outer">
<h6>Text U:</h6>
<div class="upload_section">
<button id="performance_img_20" onclick="document.getElementById('img_20').click()">Upload image</button>
<input type="file" accept="image/png, image/jpg, image/svg" id='img_20' style="display:none">
<label>Upload complete: False</label>
</div>
</div>
</div>
<div class="section_header">
<figure class="uploaded_image_container">
<img id="chosen_image">
</figure>
<div class="upload_section_outer">
<h6>Text U:</h6>
<div class="upload_section">
<button id="performance_img_21" onclick="document.getElementById('img_21').click()">Upload image</button>
<input type="file" accept="image/png, image/jpg, image/svg" id='img_21' style="display:none">
<label>Upload complete: False</label>
</div>
</div>
</div>
<div class="section_header">
<figure class="uploaded_image_container">
<img id="chosen_image">
</figure>
<div class="upload_section_outer">
<h6>Text U:</h6>
<div class="upload_section">
<button id="performance_img_19" onclick="document.getElementById('img_19').click()">Upload image</button>
<input type="file" accept="image/png, image/jpg, image/svg" id='img_19' style="display:none">
<label>Upload complete: False</label>
</div>
</div>
</div>
the problem is that it previews only on the first section, but I need to display on every individually for each upload. Additionally the text only changes for the first uploaded image and I have no clue why. Can anyone explain what I am doing wrong?
What you get here is the first chosen_image element, not the second or even the third.
const chosenImage = document.getElementById('chosen_image');
//...
chosenImage.setAttribute("src", reader.result);
//...
It is recommended to use class, So it can be
const chosenImage = document.getElementsByClassName('chosen_image')
const inputs = document.querySelectorAll('input[type=file]');
for(let i=0;i<inputs.length;i++){
input = inputs[i];
input.onchange = (e) => {
if (e.target.files.length) {
let reader = new FileReader();
console.log(e.target.nextElementSibling);
reader.readAsDataURL(e.target.files[0]);
reader.onload = () => {
chosenImage[i].setAttribute("src", reader.result);
e.target.nextElementSibling.textContent = e.target.nextElementSibling.textContent.replace(/False/, e.target.files[0].name)
}
}
}
}
enter image description here
but use for of(it is previewing in the following div ad not in the one the button is pushed)
const chosenImage = document.getElementsByClassName('chosen_image')
let i = 0;
for (const input of document.querySelectorAll('input[type=file]')) {
input.onchange = (e) => {
if (e.target.files.length) {
let reader = new FileReader();
console.log(e.target.nextElementSibling);
// do stuff
reader.readAsDataURL(input.files[0]);
reader.onload = () => {
chosenImage[i].setAttribute("src", reader.result); //edit here
e.target.nextElementSibling.textContent = e.target.nextElementSibling.textContent.replace(/False/, input.files[0].name)
}
i++;
}
}
}

Not Able to Target Closest img Element To File Input Element

Can you please take a look at this snippet and let me know why I am not able to target the closest image element to file input
$('.file').on('change', function(ev) {
var f = ev.target.files[0];
var fr = new FileReader();
fr.onload = function(ev2) {
$(this).closest('.img').attr('src', ev2.target.result);
$(this).find('.img').attr('src', ev2.target.result);
$(this).next('.img').attr('src', ev2.target.result);
};
fr.readAsDataURL(f);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" class="file" name="image" />
<img class="img" />
<input type="file" class="file" name="image" />
<img class="img" />
As you can see I already tried
$(this).closest('.img').attr('src', ev2.target.result);
$(this).find('.img').attr('src', ev2.target.result);
$(this).next('.img').attr('src', ev2.target.result);
but it is not doing the job
you have to find img closest to the input file which changes, so you must use ev.target because inside the second function scope changes and this does not refer to file input anymore, something like this seems to work:
$('.file').on('change', function(ev) {
var f = ev.target.files[0];
var fr = new FileReader();
fr.onload = function(ev2) {
$(ev.target).next('.img').attr('src', ev2.target.result);
};
fr.readAsDataURL(f);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" class="file" name="image" />
<img class="img" />
<input type="file" class="file" name="image" />
<img class="img" />

HTML multiple fileread

HTML Code:
<input type="file" name="img1" id="img1" required>
<input type="file" name="img2" id="img2">
<input type="file" name="img3" id="img3">
<input type="file" name="img4" id="img4">
jQuery Code:
for(var i = 1; i <= 4; i++){
if($("#img"+i).val() != ''){
file = document.getElementById('img' + i).files[0];
fileread(file);
}
}
function fileread(file){
var result = '';
reader = new FileReader();
reader.onload = function(){
result = reader.result;
//return result;
localStorage.setItem("lostimage1", result);
}
reader.readAsDataURL(file);
}
I want to read multiple files when user click on submit button. but it not working. How can I resolve this error? please help me.
Using Jquery and each() method I suggest this:
var checkValue;
var valueArray=[];
$('#button').on('click',function(){
$('input').each(function(){
checkValue=$(this).val();
if(checkValue===''){
return;
}
valueArray.push(checkValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="img1" id="img1" required>
<input type="file" name="img2" id="img2">
<input type="file" name="img3" id="img3">
<input type="file" name="img4" id="img4">
<button id="button">Click Me</button>
Attach click event to <input type="submit">, call event.preventDefault() to prevent <form> submission, use .each() to iterate <input type="file"> elements, pass this.files[0] to readfile function.
Adjust within FileReader load handler to not overwrite same key at localStorage.
FileReader throws an error if a Blob or File object is not passed as parameter to .readAsDataURL(), for example, ifis clicked andfilereadis called in loop and one ofelements.filesproperty doe not containFileobject inFileList. Check if element.fileshas.lengthgreater than0before callingfilereadreferencing the.files[0]property of the current` element.
$(function() {
function fileread(file, id) {
var reader = new FileReader();
reader.onload = function() {
localStorage.setItem("lostimage" + id, reader.result);
}
reader.readAsDataURL(file);
}
$("input[type=submit]").on("click", function(e) {
e.preventDefault();
$(":file[id^=img]").each(function() {
if (this.files.length) fileread(this.files[0], this.id.replace(/\D/g, ""))
})
});
});
plnkr http://plnkr.co/edit/1Sec8uWlK2pbXMTlfpCj?p=preview

Script for load image preview doesn´t work

I create script for show image until upload , how i use 5 input files for upload , the script must let show one image , or preview image for each input file
The Script :
<script>
function handleFileSelect(evt,ids) {
var files = evt.target.files;
var f = files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
document.getElementById('list'+ids).innerHTML = ['<img src="', e.target.result,'" title="', theFile.name, '" width="50"/>'].join('');
///alert("ok"+ids);
};
})(f);
reader.readAsDataURL(f);
}
</script>
HTML CODE
<input type="file" id="files2" />
<output id="list2"></output>
CALLING SCRIPT FOR THIS INPUT FILE ID
<script>
document.getElementById('files2').addEventListener('change', function(){handleFileSelect('','2');},false);
</script>
As you can see i try send vars from handleFileSelect('','2') , but don´t works never and i think the code it´s well , but sure i forget something , i hope here can help me in this issue , thank´s community
The Best Regards
Try this code
$(function () {
var _URL = window.URL || window.webkitURL;
$(".UploadImage").on("change", function () {
var preview = $(this).attr("data-img");
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
document.getElementById(preview).src = _URL.createObjectURL(file);
};
img.src = _URL.createObjectURL(file);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="file" data-img="preview1" class="UploadImage" />
<img src="" id="preview1"/>
</div>
<div>
<input type="file" data-img="preview2" class="UploadImage" />
<img src="" id="preview2"/>
</div>
<div>
<input type="file" data-img="preview3" class="UploadImage" />
<img src="" id="preview3"/>
</div>
<div>
<input type="file" data-img="preview4" class="UploadImage" />
<img src="" id="preview4"/>
</div>
It's better if you use CreateObjectURL instead (saves more memory/cpu) it's also faster
var wrapper = document.getElementById('files')
var URL = window.URL || window.webkitURL;
wrapper.addEventListener('change', function(evt){
var input = evt.target
if (input.matches('input[type="file"]') && (input.files || [])[0]) {
var img = new Image
img.width = 50
img.onload = function() {
var output = document.getElementById(input.dataset.for)
output.appendChild(this)
}
img.onerror = function(){
console.log("You uploaded something that is not an image")
}
img.src = URL.createObjectURL(input.files[0])
}
})
output {
display: block;
}
<div id="files">
<!-- Recomend adding accept attribute so you only get images -->
<!-- just made one example -->
<input type="file" data-for="list1" accept="image/*">
<output id="list1"></output>
<input type="file" data-for="list2">
<output id="list2"></output>
<input type="file" data-for="list3">
<output id="list3"></output>
<input type="file" data-for="list4">
<output id="list4"></output>
</div>

using single function how to call two different input fields

Hi in the below code I am going to upload the image using following java script function.for the first input working fine.In the same way how to call second input field when I am passing the id it's got changes the first one and second one images are displaying same.
html
<div class="person_pic">
<label>Please upload your photo</label><input type='file' name="image" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</div>
<div class="person_pic">
<label>Please upload your family photo</label>
<input type='file' name="image" onchange="readURL(this);" />
<img id="blah1" src="#" alt="your image" />
</div>
javascript
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah1')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
You can try passing the id of the img element that you want to change.As you are using $('#blah') for both the function call , hence both the time same image is being displayed.You can do this:
<script>
function readURL(input,x) {
if (input.files && input.files[0]) {
var reader = new FileReader();
x = '#'+x;
reader.onload = function (e) {
$(x)
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<div class="person_pic">
<label>Please upload your photo</label>
<input type='file' name="image" onchange="readURL(this,'blah');" />
<img id="blah" src="#" alt="your image" />
</div>
<div class="person_pic">
<label>Please upload your family photo</label>
<input type='file' name="image" onchange="readURL(this,'blah1');" />
<img id="blah1" src="#" alt="your image" />
</div>

Categories