JQuery Loop Through all File Input Fields to Get Size - javascript

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.

Related

how to hide or show a field after the form is digitally signed | Acrobat pdf forms

I have a form that needs to be digitally signed. After the form is signed, all form fields are made readonly from the properties. But my buttons are not hidden.
What can I do to hide the buttons??
PS - I am using acrobat 15
There seems to be no in-built function or property to achieve the desired result. But I got a simple javascript that I could use to make all fields readonly and hide all buttons both at the same time.
for ( var i = 0; i < this.numFields; i++) {
var fname = this.getNthFieldName(i);
if(fname.type == "button")
{
this.getField(fname).display = display.hidden;
}
else if ( fname != "Signature_2" )
this.getField(fname).readonly = true ;
}

SAP Java Script for % Increase Function

We have a Requirement, where Business always discuss to Increase or Decrease the Target sales value by some Integers, accordingly we have Input Enabled SAP WAD report which gives sale numbers. Moreover Now we have developed all of the Necessary Configuration to perform this %Increase Function but need this precise Javascript code optimization on my existing code.
Logic is, I Select the Required multiple row Cells and subsequently admit to press the %Increase Button, a Prompt will pop-up and enter the required integer Values and say OK.
So,for that Input provided integer value, back-end code should perform the %Increase calculation and insert back to respective cell.
x = (Input Value/100)X Cell Value;
Result = Cell value X x
Here I need your help fix the Javascript syntax correction.
The below Code performs 80% of my required function, but only need 20% of modification on that.
function sapbi_rig_plan_Per_Increase(content){
if ('undefined' == typeof(content) ) content = '';
if (content == null) content = '';
var info = sapbi_rig_plan_inf;
if (sapbi_rig_plan_isValidState(info) === false){
alert('Please select the range.');
return;
}
var content = prompt("Please enter value", " ");
if (isNumber(content ) == true){
var cell;
for(var cntSel = 0; cntSel<info.activeSel.length; cntSel++){
cell = document.getElementById(info.activeSel[cntSel][0]);
var fact = (content/100)*cell;
var content1 = fact+cell;
sapbi_rig_plan_setContent(cell, content1);
}
} else {
alert('Please Enter the Valid Qty only');
}
}
Please Note : I am Not java Developer, i am SAP BW-IP Developer

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" />

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

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");
});
}
});
});

$_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