How to preview image when upload to multiple forms - javascript

I have 2 image upload forms, when one is uploaded it should show a preview of the uploaded image. However, when I upload an image in one of the input forms, both forms display a preview of the last uploaded image. How do I make the preview only appear on the uploaded form?
Here's my code :
<div class="container">
<form action="save.php" method="post" enctype="multipart/form-data">
<!-- rows -->
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview1" class="img-thumbnail1">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img1" class="file1" id="file1">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image1" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview2" class="img-thumbnail2">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img2" class="file2" id="file2">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image2" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<button type="submit" name="btn_save" class="btn btn-success">Save</button>
</form>
</div>
<script>
$(document).on("click", "#select_image1", function() {
var file = $(this).parents().find(".file1");
file.trigger("click");
});
$('input[type="file"]').change(function(e) {
var fileName1 = e.target.files[0].name;
$("#file1").val(fileName1);
var reader = new FileReader();
reader.onload = function(e) {
// get loaded data and render thumbnail.
document.getElementById("preview1").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(e.target.files[0]);
});
// 2
$(document).on("click", "#select_image2", function() {
var file2 = $(this).parents().find(".file2");
file2.trigger("click");
});
$('input[type="file"]').change(function(el) {
var fileName2 = el.target.files[0].name;
$("#file2").val(fileName2);
var reader2 = new FileReader();
reader2.onload = function(el) {
// get loaded data and render thumbnail.
document.getElementById("preview2").src = el.target.result;
};
// read the image file as a data URL.
reader2.readAsDataURL(el.target.files[0]);
});
</script>
I've tried changing the script code, but it doesn't work. Please help. Thank you.

Related

Upload or Draw Signature on Laravel form

I used this https://www.itsolutionstuff.com/post/laravel-signature-pad-example-tutorialexample.html to create a signature pad. I am looking for a way to add an option to upload a signature or use the pad to draw a signature.
Here's what I wrote:
Laravel Blade Code
<form method="POST" action="{{ route('signaturepad.upload') }}">
<div class="tab-content">
<div class="tab-pane fade show active" id="draw">
<div class="col-md-12">
<label class="" for="">Draw Signature:</label>
<br/>
<div id="sig"></div>
<br><br>
<button id="clear" class="btn btn-danger">Clear Signature</button>
{{--<button class="btn btn-success">Save</button>--}}
<textarea id="signature" name="signature" style="display: none"></textarea>
</div>
</div>
<div class="tab-pane fade" id="upload">
<label class="" for="">Upload Signature:</label>
{{--<div class="form-group"></div>
<input type="file" name="file" id="file" required>--}}
{{--<button type="submit">Submit</button>--}}
</div>
<button class="btn btn-success">Save</button>
</div>
</form>
Javascript
<script src="{{ asset('js/pages/jquery.signature.js')}}"></script>
<script type="text/javascript">
var sig = $('#sig').signature({syncField: '#signature', syncFormat: 'PNG'});
$('#clear').click(function(e) {
e.preventDefault();
sig.signature('clear');
$("#signature").val('');
});
</script>
Controller
if(!empty($request->input('signature')) || (!empty($request->input('file')))) {
echo $request->signature;
echo $request->file;
dd('passed');
//$folderPath = public_path('uploads/');
//$data_uri = $request->signature;
//$encoded_image = explode(",", $data_uri)[1];
//$decoded_image = base64_decode($encoded_image);
//$file = $folderPath . uniqid();
//file_put_contents($file, $decoded_image);
return view('dashboard');
} else {
//dd('Signature is empty.');
return back()->withErrors(['msg', 'Signature Empty']);
}
Drawing the Signature works when one of the file uploads is commented out. When both are active they don't post and both don't work. My question is how do I work with both where one can either draw or upload the signature. I have tried if statements in the controller to no avail.
Thanks in Advance!

I can't reset input file inside form after submit

I have a form with some fields and after submit finish i want to reset whole form but only reset input text areas not input type file.
I check every similar questions and solutions but none of them work for me.Some solutions refresh page which i don't want that.
<form class=" dropzone px-5" id="mydropzone">
<h2 class="text-center">Lets create your menu</h2>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCalories">Calorie</label>
<input type="text" class="form-control" id="inputCalories" required>
</div>
<div class="form-group col-md-6">
<label for="cc">Calorie Calculator</label>
<button id="cc" class="btn btn-primary btn-lg"><i class="fas fa-calculator mr-2"></i>Click Me</button>
</div>
</div>
<div class="form-row">
<div class="form-group ml-2 col-sm-6">
<label>Menu Item Image</label>
<div id="msg"></div>
<div class="progress" id="uploader">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%"></div>
</div>
<input type="file" name="img[]" class="file" accept="image/*" id="fileButton">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file" required>
<div class="input-group-append">
<button type="button" class="browse btn btn-primary"><i class="fas fa-folder-open mr-2"></i>Browse...</button>
</div>
</div>
<div class="ml-2 col-sm-6">
<img src=" " id="preview" class="img-thumbnail">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block mb-3">Submit Menu</button>
<!-- -------------------------------------------------------------------------- -->
</div>
</form>
And my create menu which clear all fields after form submit.
// create menu
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file = e.target.files[0];
var storageRef = firebase.storage().ref('foodImg/' + file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
console.error(error);
}, function() {
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
const createMenuForm = document.querySelector('#mydropzone');
createMenuForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('restaurants').add({
foodLine: {
menuTitle: createMenuForm.menuTitle.value
},
food: {
foodName: createMenuForm.foodName.value,
imageURL: downloadURL,
inputCalories: createMenuForm.inputCalories.value,
menuItemDescription: createMenuForm.menuItemDescription.value,
menuItemInfo: createMenuForm.menuItemInfo.value
}
}).then(() => {
//reset form
createMenuForm.reset();
fileButton.value = "";
var preview = document.getElementById('preview');
preview.value = "";
}).catch(err => {
console.log(err.message);
});
});
});
});
});
Can you try these things also
document.getElementById("myForm").reset();
$("#myForm").trigger("reset");
I think you try to access createMenuForm outside the scope where const createMenuForm was declared.
Try to declare it above the event listener:
// create menu
const createMenuForm = document.querySelector('#mydropzone');
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// ...
or directly with
document.querySelector('#mydropzone').reset();
i debug and find that preview need to be clean
document.getElementById("preview").src = "#";

File data not visible in textarea but can see it in console.log using getElementsByClassName

Here I am trying to read the first file and trying to display it in the text area when I hit button RUN. When I use getElementByID, I get the error
Uncaught TypeError: Cannot set property 'value' of null
But getElementByID works when I put text area in the same same <div> tag where the button RUN is present. But I am supposed to use the below format but I get error. I do not get any error with getElementsByClassName but I can just see the value in console.log but its not displayed in text area.
function loadFileAsText(){
var fileToLoad = document.getElementById("fileUploader").files[0];
var textFromFileLoaded;
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
textFromFileLoaded = fileLoadedEvent.target.result;
console.log(textFromFileLoaded);
document.getElementsByClassName("classTextarea")[0].value = textFromFileLoaded;
console.log(document.getElementsByClassName("classTextarea").value);
};
fileReader.readAsText(fileToLoad);
}
<div class="button files">
<input id="fileUploader" type="file" multiple="multiple">
</div>
<div class="button run">
<span type="button" onclick="loadFileAsText()">Run</span>
</div>
<article class="editor multiline">
<div class="pad">
<textarea id="idTextarea" class="classTextarea">
</textarea>
</div>
</article>
document.getElementsByClassName("classTextarea") returns an array of elements, you need to choose the the first:
function loadFileAsText() {
var fileToLoad = document.getElementById("fileUploader").files[0];
var textFromFileLoaded;
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
textFromFileLoaded = fileLoadedEvent.target.result;
console.log(textFromFileLoaded);
document.getElementsByClassName("classTextarea")[0].value = textFromFileLoaded;
console.log(document.getElementsByClassName("classTextarea")[0].value);
};
fileReader.readAsText(fileToLoad);
}
.as-console-wrapper {
max-height: 40px !important;
}
<div>
<div class="button files">
<input id="fileUploader" type="file" multiple="multiple">
</div>
<div class="button run">
<span type="button" onclick="loadFileAsText()">Run</span>
</div>
</div>
<article class="editor multiline">
<div class="pad">
<textarea id="idTextarea" class="classTextarea">
</textarea>
</div>
</article>
changing just document.getElementsByClassName("classTextarea") to document.getElementsByClassName("classTextarea")[0] works flawlessly. You only get the undefined error when you do not choose a file.
function loadFileAsText(){
var fileToLoad = document.getElementById("fileUploader").files[0];
var textFromFileLoaded;
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
textFromFileLoaded = fileLoadedEvent.target.result;
console.log(textFromFileLoaded);
document.getElementsByClassName("classTextarea")[0].value = textFromFileLoaded;
console.log(document.getElementsByClassName("classTextarea")[0].value);
};
fileReader.readAsText(fileToLoad);
}
<div class="button files">
<input id="fileUploader" type="file" multiple="multiple">
</div>
<div class="button run">
<span type="button" onclick="loadFileAsText()">Run</span>
</div>
<article class="editor multiline">
<div class="pad">
<textarea id="idTextarea" class="classTextarea">
</textarea>
</div>
</article>

Get the ID of the label associated with the input type file field

I have a requirement where I have to get the ID of the label associated with the input type file field. I have a set of 4 input type file fields with id's photo1, photo2, photo3, photo4. The labels associated with these file fields are label-1, label-2, label-3 and label-4 respectively. My requirement is that I want to get the respective label fields and update the text of the label. This is what I have tried so far.
<div class="koh-contact-photo">
<span><fmt:message key='photo1' /></span> <label id="upload-1" class="button-default" ><fmt:message
key='photo.upload' /></label>
<div id="preview-1" class="preview"></div>
<button type="button" class="koh-photo-remove remove-button">
<span class="icon" data-icon="&#xe605"></span> <span
class="label"><fmt:message key='photo.remove.text' /></span>
</button>
<!-- The Modal -->
<div id="myModal1" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<h3 class="modal-title"> Upload Photo </h3>
<div class="modal-inner">
<span>Browse for a photo</span> <label id="label-1" style="margin-bottom:20px;" class="button-default browse" for="photo1">BROWSE</label><input id="photo1" type="file"
name="photo1" data-parsley-filesize="3"
data-parsley-filetype="image/jpeg, image/png, image/gif, image/bmp"
data-parsley-trigger="change" />
<hr class="modal-hr" />
<div class="guidelines-modal">
<p> GENERAL GUIDELINES </p>
<p> Supported files are: .jpg, .gif, .png, .bmp </p>
<p> Maximum File Size: 3MB</p>
<p style="margin-bottom:10px;"> For best results: upload at 400 x 300</p>
<p> Note: images are automatically resized</p>
</div>
<div class="koh-contact-captcha modal-hr">
<!--div class="g-recaptcha" data-sitekey=<fmt:message key='kohlerSterling.google.captcha.key' />></div-->
<!--div class="g-recaptcha" id="recaptcha1"></div-->
<div id="recaptcha3" class="captcha"></div>
<div class="error-message">
<span><fmt:message key='required.field.text' /></span>
</div>
</div>
<div class="terms-modal">
<div class="checkbox">
<input type="checkbox" id="terms-condns" required/>
<label style="font-family:Helvetica Neue LT Pro Roman !important;font-size:12px !important;color:#000 !important;font-weight:400 !important;" for="terms-condns">I agree to the <a class="modal-anchor" href="#">Terms and Conditions</a></label>
</div>
</div>
<hr class="modal-hr" />
<div class="modal-buttons">
<label class="button-default-modal" style="margin-right:20px;">CANCEL</label>
<label id="input-button-modal-1" class="input-button-modal">UPLOAD</label>
</div>
</div>
</div>
<input type="hidden" id="captchaKey" value="<fmt:message key='google.recaptcha.site.key'/>">
</div>
</div>
I have 4 such div classes. and this is the javascript.
$contactPhotos.each(function () {
var $photoInput = $(this).find("input[type=file]");
var img = $("<img />");
var photoPreview = $photoInput.parent().parent().parent().parent().find(".preview").attr("id");
var photoPreviewImg = $("#" + photoPreview);
function readURL(input) {
if (input.files && input.files[0]) {
photoPreviewImg.html("");
//alert(JSON.stringify(photoPreviewImg, null, 4));
var reader = new FileReader();
reader.onload = function (e) {
img.attr("style", "height:41px;");
img.attr("style", "width:210px;");
img.attr("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(this).on('click','.input-button-modal', function(e) {
var contactModal = $(this).parent().parent().parent().parent().parent().find(".modal").attr('id');
var currentModal = $('#' + contactModal);
currentModal.attr("style", "display:none");
photoPreviewImg.append(img);
});
$photoInput.parsley().on('field:success', function() {
var inputID = $photoInput.attr('id');
var inputTarget = '#' + inputID;
var inputValue = document.getElementById(inputID);
//inputLabel.attr("style", 'width:70%;');
readURL(inputValue);
$(inputTarget).parent().parent().parent().parent().find('.koh-photo-remove').show();
$contactForm.find('#terms').prop('required',true);
});
});
Any help is appreciated. I want to get the ID of the label associated with each of the input type file field. Thanks in advance.
Label and input fields are linked by the for of the label being the id of input. You can simply take advantage of that link
function getLabelID(input){
return $("label['for=" + $(input).attr("id") + "']").attr("id");
}

How to send cropped image with form post

How can I handle cropped image and send with post? I am using Cropper.js library. The HTML codes already in a form element. These codes copied from sample admin template. Cropping works but I cant send files.
HTML:
<div class="row">
<div class="col-md-6">
<div class="image-crop">
<img src="{{ asset('backend/images/image-upload.png') }}">
</div>
</div>
<div class="col-md-6">
<h4>Preview image</h4>
<div class="img-preview img-preview-sm" style="width: 180px;height:180px;"></div>
<hr>
<div class="btn-group">
<button class="btn btn-white" id="zoomIn" type="button">Zoom In</button>
<button class="btn btn-white" id="zoomOut" type="button">Zoom Out</button>
<button class="btn btn-white" id="rotateLeft" type="button">Rotate Left</button>
<button class="btn btn-white" id="rotateRight" type="button">Rotate Right</button>
</div>
<hr>
<div class="btn-group">
<label title="Upload image file" for="inputImage" class="btn btn-primary">
<input type="file" accept="image/*" name="file" id="inputImage" class="hide">
Upload new image
</label>
<label title="Donload image" id="download" class="btn btn-primary">Download</label>
</div>
</div>
JS:
var $image = $(".image-crop > img")
$($image).cropper({
aspectRatio: 1,
preview: ".img-preview",
done: function(data) {
// Output the result data for cropping image.
}
});
var $inputImage = $("#inputImage");
if (window.FileReader) {
$inputImage.change(function() {
var fileReader = new FileReader(),
files = this.files,
file;
if (!files.length) {
return;
}
file = files[0];
if (/^image\/\w+$/.test(file.type)) {
fileReader.readAsDataURL(file);
fileReader.onload = function () {
$inputImage.val("");
$image.cropper("reset", true).cropper("replace", this.result);
};
} else {
alert("Please upload a image file");
}
});
} else {
$inputImage.addClass("hide");
}
//Disabled Cropped Image Download
/*
$("#download").click(function() {
window.open($image.cropper("getDataURL"));
});
*/
PHP:
var_dump($_FILES);
Post Output:
you do it as a canvas first and get the base64 string toDataURL("image/png") then catch it in your server side and convert it to image again using the base64 string
kindly take a look at this post.
Convert an image into binary data in javascript

Categories

Resources