JavaScript function called only once instead of every time - javascript

I need a javascript code that checks the input file size before uploading everytime the input value changes (i.e. everytime the user selects a file to upload).
So far I came up with this:
var file = document.getElementById("myFile");
file.addEventListener('change', function() {
if (this.files[0].size > 2*1024*1024) {
alert('Max file size is 2 MB');
file.removeAttribute('value');
file.parentNode.replaceChild(file.cloneNode(true),file);
}
}
);
and the HTML is:
<form action="?" method="post">
<input type="file" id="myFile" name="myFile" />
<input type="submit" value="upload" />
</form>
Now, if I leave the Javascript code like that, it doesn't work at all.
But if I change it like this
window.onload = function() {
// Same code above
}
it works, but only for the first file the user selects.
How can I change it to make it work everytime the user selects a file? (if possible without jQuery)

No need to clone the node etc ... just set the value to '';
file.value = '';
see working snippet
document.getElementById("myFile").addEventListener('change', function() {
if (this.files[0].size > 2*1024*1024) {
alert('Max file size is 2 MB');
this.value='';
}
});
<form action="?" method="post">
<input type="file" id="myFile" name="myFile" />
<input type="submit" value="upload" />
</form>

From the documentation for cloneNode:
Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener()
You are deleting the element with the event handler on it and replacing it with one that doesn't have a change listener
You need to call addEventListener again (and store file.cloneNode(true), in a variable so you can call addEventListener on it and pass it to replaceChild).

Related

HTML file input event listener not firing when removing selected file path

So I have a input type="file" in my html and a change EventListener which works properly. I now added a remove button which basically works like this:
function removeFile(){
document.getElementById("fileinput").value = "";
}
Simply setting the value of the file input to an empty string. But this does not trigger the event listener. How can I make this work?
Thanks,
Johannes
run ok
function removeFile(){
document.getElementById("fileinput").value = "";
}
document.querySelector('#btn1').addEventListener('click', function(){
removeFile()
})
<input type="file" name="" id="fileinput">
<button onclick="removeFile()">removeFile</button>
<button id="btn1">removeFile</button>

Form's uploaded file disappears on canceling new selection of file

I have a simple form on my webpage.
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input id="browse" type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Now, my problem is when I browse and choose file to upload it shows which file I am going to upload.
But when I click on Choose file and browse again and this time if I change my mind mid way and hit cancel then old selected image also goes away.
On canceling it removes already selected image also.
Why does this happen and what to do if I want my old selected image to be selected after browsing again and canceling?
Thanks in advance!
Thanks to #Carlos , added this javascript
var input = document.getElementById("browse");
var selectedFile;
input.addEventListener('change', updateImageDisplay);
function updateImageDisplay() {
if(input.files.length==0) {
input.files = selectedFile;
}
else {
selectedFile = input.files;
}
}
and now it works fine! you can check here.

HTML file input with possibility to input several files one after another

I'm looking for a possibility to input several files in a row in an HTML form. It strikes me that there seems to be no easy solution for this (or at least I haven't been able to find it despite several hours of searching). If I use the multiple attribute in an <input type="file" name="myFiles[]" multiple />, I can choose several files at a time holding Ctrl, but if I choose one file at first, then click the input field again and choose another one, the second file seems to overwrite the first one.
So I thought I might try to use javascript to add more <input type="file" name="myFiles[]" /> fields (with the same name), since I have seen something similar somewhere. I tried the following:
JavaScript:
function addInputFileEle() {
var field = document.getElementById("filesField");
var row = '<input type="file" name="myFiles[]" onchange="addInputFileEle();" />';
field.innerHTML += row; // add one more <input type="file" .../> element
}
HTML:
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesField"> <!--for adding more file-input rows-->
<input type="file" multiple name="myFiles[]" class="multi" onchange="addInputFileEle();" />
</fieldset>
<input type="submit"/>
</form>
The document indeed does create additional file-input elements whenever I click on one of them and select a file, BUT: The file does not get uploaded! I mean, after I select the file, the file name does not get displayed, instead, it still says "Choose a file" (or "Select a file", not sure about English). So apparently my onchange="addInputFileEle()" overwrites the normal reaction (the file getting 'loaded' into the input element)? Even though this does not seem logical to me. Can anyone help? Why does the file not get selected in the end? Or maybe there is a simpler solution than mine, which would of course be very welcome. Thanks in advance!
Ok I will just post my solution in case anyone else is searching for a way to select several files for upload one by one. As #CodingWithClass pointed out, I was resetting the input field by using something like parentElement.innerHTML += additionalInputElement;. Instead, I should have used appendChild as #JoshuaK suggested:
<html>
<head>
<meta charset="UTF-8">
<script>
function addFileInput(fieldsetName, firstInputId) {
var fs = document.getElementById(fieldsetName);
// only add one if the last file-input field is not empty
if(fs.lastElementChild.value != '') {
var firstInputFile = document.getElementById(firstInputId);
var newInputFile = document.createElement("input");
newInputFile.type = firstInputFile.type;
newInputFile.name=firstInputFile.name;
newInputFile.multiple=firstInputFile.multiple;
newInputFile.class = firstInputFile.class;
newInputFile.onchange=firstInputFile.onchange;
fs.appendChild(newInputFile);
}
}
</script>
<title>MultiFile-Testing</title>
</head>
<body>
<?php print_r($_FILES); // see if files were uploaded in the previous round ?>
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesFS">
<input type="file" multiple name="myFiles[] id="firstInputFile" onchange="addFileInput('filesFS', 'firstInputFile');" />
</fieldset>
<input type="submit"/>
</form>
</body>
</html>

Upload file not working in Chrome extension option page

I am developing a chrome extension with an option page. On that page I put an upload image option but can't get the file to load in javascript. I have tried many solutions (1st solution, 2nd solution ...) but none worked. The strange thing is, that even an "onclick" attribute in the html code doesn't call the corresponding function. Here is an example of the code:
HTML example:
<input type="file" name="uploadImage" id="uploadImage" />
<button type="submit" id="imageUpload-btn" onclick="myFunction();">Upload</button>
javascript example:
jQuery("#imageUpload-btn").click(function(){
var image = new Image();
image.src = jQuery("#uploadImage").val();
alert(image.src);
image.onload = function(){
alert("on load");
}
image.onerror = function(){
alert("error");
}
});
I get the path of the file in the first alert, but then always the error alert. The function "myFunction()" is not called, but if I open the file directly in a browser the "onclick" trigger works and "myFunction()" is called.
What am I doing wrong or what am I missing?
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <INPUT type="file" name="submitfile" id = "submitfile" />
<INPUT type="button" value="Send" onClick="checkSize();" />
</form>
here you are using enctype="multipart/form-data" in this type we dont have opertunity to use
im.src = document.getElementById('submitfile').value;
you need to go for apache.commons.fileupload ServletFileUpload.isMultipartContent(request); which is totally java related.

Making function work for any one of the same type of element

I am trying to create a file upload system. This file upload system works great for the mosot part. The problem comes in because there are multiple HTML elements on the page that have class file and multiple HTML elements that are upload-buttons. Right now file uploading works great only for the first HTML element that contains the upload text field and upload button only, all others fail to work (due to Javascript selecting the [0] object every time).
My question is, how can can I adjust the function below to cater to whatever upload container / button that was used?
Essentially what needs to happen is, if the user clicks on the nth upload button the functions array slots needs to be equal to n-1 somehow.
I appreciate any assistance with this problem.
Many thanks in advance!
$(document).on('click','.upload-button', function(){
var data = new FormData();
jQuery.each($('.file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
//Some more code...
});
HTML
<div class="input-text-field">
<input name="userfile" class="file" type="file" />
<input class="submit upload-button" type="submit" value="Upload" />
</div>
Use prev() to target just the previous .file element, and be aware that your code does'nt have a .file element, it has a #file element, and multiple ID's are invalid.
$(document).on('click','.upload-button', function(){
var data = new FormData();
jQuery.each($(this).prev('.file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
//Some more code...
});
html
<div class="input-text-field">
<input name="userfile" class="file" type="file" />
<input class="submit upload-button" type="submit" value="Upload" />
</div>

Categories

Resources