$('element').click() not working - javascript

This is my file input element:
<input type="file" id="StudentPhoto" value="StudentPhoto" style="display: none;">
This is the validation function:
$(document).ready(function() {
$('#StudentPhoto').change(function()
{
var file_data = $("#StudentPhoto").prop("files")[0];
var size = file_data.size;
var type = file_data.type;
var name = file_data.name;
var input = $("#StudentPhoto");
if(type !== 'image/png' && type !== 'image/jpg' && type !== 'image/jpeg')
{
alert("Only JPG & PNG files are allowed to upload as student photo.");
$('#StudentPhoto').click();
}
else if(size > 2097152)
{
alert("The maximum photo size is 2MB\n");
$('#StudentPhoto').click();
}
});
});
If the file chosen by the user has an invalid format or size, it's supposed to pop up the dialog to ask him to choose the file again, but it doesn't, the statement $('#StudentPhoto').click(); in the function doesn't work. Why? Is there any other method?

Or you can use the .trigger() method to make the click event fire on the button. We'll also use input since you stored the file field already.
input.trigger('click');
Hope this helps.

You can use HTML DOM click() method:
document.getElementById('StudentPhoto').click();

Change your file input element to:
<input type="file" id="StudentPhoto" value="StudentPhoto" style="visibility: hidden">
Note that I used visibility: hidden, instead of display: none.
You cannot call the click event on a non-displayed file input.

you need to insert your callback withing the click event:
$(document).ready(function()
{
$('#StudentPhoto').change(function()
{
var file_data = $("#StudentPhoto").prop("files")[0];
var size = file_data.size;
var type = file_data.type;
var name = file_data.name;
var input = $("#StudentPhoto");
if(type !== 'image/png' && type !== 'image/jpg' && type !== 'image/jpeg')
{
alert("Only JPG & PNG files are allowed to upload as student photo.");
$('#StudentPhoto').click();
}
else if(size > 2097152)
{
$('#StudentPhoto').click(function(){
alert("The maximum photo size is 2MB\n");
});
}
});
});

Related

5 file fields, 1 validation for all

I have 5 file inputs that I perform a file validation using the following code:
$("#fileinput").change(function() {
var file = this.files[0];
var fileType = file.type;
var match = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
if(!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3]) || (fileType == match[4]) || (fileType == match[5]))){
Swal.fire("Erro: Invalid file format!", "Only: PDF, JPG, JPEG e PNG", "error");
$("#docpessoal").val(null);
$(".custom-file-label").text('Selecionar documento...');
return false;
}
});
Instead of repeating the function for each file input I would like to to use the same function but changing the selector ID based on which input the user clicked. (I'm not sure if it's possible)
Heres the code that I tried to do that:
var nomeInput = '_';
$('input[type="file"]').click(function(){
var nomeInput = $(this).attr('id');
});
I tried to use the variable nomeInput in the .change selector but it doesn't work.
Is there anyway to achieve that?
Delegate the change event to the form, in the handler, get a reference to the changed input via the event object, you don't need any messy identifiers or DOM traversing in the handler function. Like this:
$('.validate-form').on('change', '[type="file"]', e => {
const type = e.target.files[0].type;
if (!/application\/pdf|image\/jpe?g|image\/png/.test(type)) {
console.log('Filetype doesn\'t match.');
} else {
console.log('Accepted filetype.')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="validate-form">
<input name="dummy">
<br>
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
</form>
If the form contains file inputs you don't want to validate, group the wanted inputs with a class, and attach the listener using that class instead of more general attribute selector.

How to not open File upload when parameters are not meet javascript

How to not open the file upload box when input mytextField is null.
<input type="text" id="mytextField">
<input type="file" multiple id="myFileUpload">
<script>
document.getElementById("myFileUpload").addEventListener("click", function () {
var myTextF = document.getElementById("mytextField");
if(myTextF = null || myTextF == ''){
//will not open the file upload
} else {
//let the file upload open
}
});
</script>
You can disable the upload button when textarea is empty and enable it when textarea contains text.
<input type="text" onkeyup="checkField()" id="mytextField">
<input type="file" multiple id="myFileUpload" disabled="disabled">
script:
function checkField(){
var myTextF = document.getElementById("mytextField");
if(myTextF.value.trim() != ""){
document.getElementById("myFileUpload").disabled = false;
}
}
Used the trim() function to prevent empty whitespace texts.
Here you are assigning myTextF to the element, rather than the innerText.
Try with var myTextF = document.getElementById("myTextF").innerText;
If something doesn't work, you could always try to log the output to the console.
In this case, because you are assigning the element, that resolves as TRUE, and it will always try to open the file.
document.getElementById("myFileUpload").addEventListener("click", function () {
var myTextF = document.getElementById("mytextField");
if(myTextF = null || myTextF == ''){
//will not open the file upload
console.log("I should not open file")
} else {
//let the file upload open
console.log("I should open the file")
}
});
" I should open the file"

JQuery Loop Through all File Input Fields to Get Size

I'm trying to loop through all file input fields and set an error message if any are over 5MB as a first step to form validation.
I'm using a click event on the submit button. The problem is that "key" is not defined.
This form can have up to 10 file input fields, added via AJAX called images[]
/* loop through all file inputs to check size */
$("#my-form").find("input[type='file']").each(function(key, value) {
var el = this.files[key];
if(el.size > 5242880 || el.fileSize > 5242880) {
errorMessage = 'Files must be less than 5MB.';
}
});
If I use this.files[0] I can get the first field's size, but having trouble looping through all elements. Appreciate your input or other solutions. Thanks much!
You could do this
$("#my-form").find("input[type=file]").each(function(index, field){
const file = field.files[0];
if(file.size > 5242880 || file.fileSize > 5242880) {
errorMessage = 'Files must be less than 5MB.';
}
});
Here is a fiddle: https://jsfiddle.net/kmm67nLz/
For file inputs with multiple attribute
$("#my-form").find("input[type=file]").each(function(index, field){
for(var i=0;i<field.files.length;i++) {
const file = field.files[i];
if(file.size > 5242880 || file.fileSize > 5242880) {
errorMessage = 'Files must be less than 5MB.';
alert(errorMessage);
}
}
});
Here is a fiddle: https://jsfiddle.net/kmm67nLz/1/
The second one is perfect to use in any of single or multiple file input.

Combining file size check and file type check - JS validation

So I am trying to validate file uploading before the file itself is uploaded and would like to check for two conditions - whether or not the file is smaller than 5mb and whether or not the file is in an image format.
This is how I am doing it at the moment:
<script>
$(document).ready(function () {
$('input[type=file]').change(function () {
var fileSize = this.files[0].size/1024/1024;
if (fileSize > 5) { alert("Please check the size of your image");
$(this).val('');
}
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(png|jpg|jpeg|gif)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Only image files are supported. Please check the format of your file and try again.');
}
});
});
</script>
It works fine except that if the file is too big and it is removed, the alert for wrong file type fires too because the input has changed.
Is there any better way to get around this? I'd like to check both conditions without the user getting warned about file format if only the image size is wrong. Could I kill the second function if the first one is triggered?
Here is what you can do, create and manage an array of errors, and use it at the end. Click run to see the demo
$(document).ready(function() {
$('input[type=file]').change(function() {
var file = this.files[0],
val = $(this).val().trim().toLowerCase();
if (!file || $(this).val() === "") { return; }
var fileSize = file.size / 1024 / 1024,
regex = new RegExp("(.*?)\.(png|jpg|jpeg|gif)$"),
errors = [];
if (fileSize > 5) {
errors.push("Please check the size of your image");
}
if (!(regex.test(val))) {
errors.push('Only image files are supported. Please check the format of your file and try again.');
}
if (errors.length > 0) {
$(this).val('');
alert(errors.join('\r\n'));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" />

$_FILES Array empty after submiting form with input file

I have a form where you have to add an image, either by adding a link or uploading an image. When you load the page there is an input text for the url, and there is a button I scripted to change the HTML of the input text to the input file one.
That works well, but the problem comes when submitting the form, the $_FILE array of that dynamic upload input doesn't exist.
This is the javascript code to swap the input:
function SwapImageMode()
{
if(imageMode == 0)
{
imageMode = 1;
$("#f_imagearea").html("<input type='file' name='addon_imgupld' id='f_upimgimput' name='addon_imgupld' style='margin-bottom:7px;' accept='image/*' onchange='inputFileChange();'/>");
}
else if(imageMode == 1)
{
imageMode = 0;
$("#f_imagearea").html("<input type='text' name='addon_imgurl' class='styled_imput f_imgimput' onFocus=imgUrlImputFocus(); onBlur=imgUrlImputBlur(); />");
}
}
Php code when the form is submitted:
if(isset($_POST["addon_imgurl"]) && !isset($_POST["addon_imgupld"]))
{
$formImgMethod = 1; // link
}
else if(isset($_POST["addon_imgupld"]) && !isset($_POST["addon_imgurl"]))
{
$formImgMethod = 2; // upload
}
if($formImgMethod == 2)
{
echo($_FILES["addon_imgupld"]["name"]);
}
And this is the error of php:
Notice: Undefined index: addon_imgupld in
C:\xampp\htdocs\addexp\agregar\index.php on line 49
The error is pretty straight-forward. You are trying to access an array key that doesn't exist, so you'll need to check for different types of form submissions.
Just write a simple conditional in your PHP form handler:
if( !empty($_FILES["addon_imgupld"]) ){
//file input
} elseif( !empty($_REQUEST["addon_imgurl"]) ) {
//text input
} else {
//error?
}
You'll want to swap $_REQUEST with whatever type of request was made ($_POST, I assume...).
UPDATE::
This conditional is wrong:
else if(isset($_POST["addon_imgupld"]) && !isset($_POST["addon_imgurl"]))
Should be:
else if(isset($_FILES["addon_imgupld"]) && !isset($_POST["addon_imgurl"]))
UPDATE 2::
Did you set your form encoding type to multipart? If not, add this attribute to your form tag:
enctype="multipart/form-data"

Categories

Resources