How to remove image input with required field by using javascript - javascript

I did a script that check the image width and remove the image if the width is lesser than certain amount.
The image field is required and after I removed it, it still passed the file validation.
sample: http://jsfiddle.net/AUQYv/3/
<form action="">
<input type="file" id="file" required />
<input type="submit" value="Submit">
</form>
Javascript
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
if(this.width<490||this.height<175){
$("#file").val("").change();
}
};
img.onerror = function () {
alert("not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});

Your conditional statement is setting file = this.files[0]. Change to ==
Edit:
Since both commenters pointed out that I was wrong, replace
$("#file").val("").change():
with
$("#file").replaceWith($("#file").clone());

Try with this.
<form action="" id="form" method="post">
<input type="file" id="file" required accept='image/png, image/gif, image/jpeg, image/jpg'/>
//your button submit
Submit
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//When click the button
$('#submitForm').click(function(){
var validation = true; //Var to validation true
if($('#file').val()){ //There's image?
if($('#file').width()<490 || $('#file').height()<175){
validation = false;
}
}else{
validation = false;
}
//Is true?
if(validation){
$('#form').submit();
}else{
alert("select a image");
}
});
</script>

Related

how to prevent input type file from accepting some inputs on change function

I'm working on a project and I need the user to upload only pdf files.
I'm trying to do this in the front-end so whenever the input detects a file type that is not a pdf should reject it. Everything seems correct. However, when I hover over the input it shows me that the wrong file is uploaded. So what should I do?
function changeName(elem) {
$("input[type='file']").
elem.on("change", function() {
var fileName = elem.val().split("\\").pop();
var fileExtension = elem.val().split(".").pop();
if (fileExtension === "pdf") {
elem.siblings(".Syllabus").text(fileName);
} else {
elem.siblings(".Syllabus").val('');
elem.siblings(".Syllabus").text('...');
alert('Only PDF files are accepted');
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="Syllabus fileReset">...</label>
<input type="file" accept="application/pdf" name="file1" onClick="changeName($(this));" required class="upload-button removable" />
This code works better than what you posted
$("input[type='file']").on("change", function(e) {
var elem = $(this);
elem.siblings(".Syllabus").text("...")
var fileName = elem.val().split("\\").pop();
var fileExtension = elem.val().split(".").pop();
if (fileExtension !== "pdf") {
elem.siblings(".Syllabus").text('Only PDF files are accepted')
elem.replaceWith(elem.val('').clone(true));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="Syllabus fileReset">...</label>
<input type="file" accept="application/pdf" name="file1" required class="upload-button removable" />

Image does not load properly

i am trying to make a simple page im HTML/javascript. The point is to check some parameters (width, height...) of an image that the user submit a form. In JS i get the file from the form, and try to "convert" it to an image using Object URL.
Problem happens there, when i load the url into the image .src property, the image does not seem to load well. Its attributes keep the default values (width=0, name =""...) and the .onload event isn't even triggered.
A simplified version of my code is below.
The url works well when i copy/paste it in my browser I get the image I submited. Neither the .onload or .onerror function is called.
I don't get why the image isn't loaded properly. If anyone has a clue I'll be glad if you share it.
function checkData() {
var images = document.getElementsByName('img');
var img = new Image();
img.onload = function() {
alert('the image is drawn');
}
img.onerror = function(e) {
console.log("Not ok", e);
}
img.src = URL.createObjectURL(images[0].files[0]);
if (img.width != 385 || img.height != 345) {
alert("Wrong size");
return false;
}
}
console.log();
<form method=POST name="Form" onsubmit="return checkData()" action="">
Image 1
<input type="file" name="img"><br>
<input type="submit" value="check">
</form>
This will draw a user uploaded image to a canvas. I think that's what you're going for?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method=POST name="Form" action="">
Image 1
<input type="file" onchange="previewFile()"><br>
<canvas id="canvas"></canvas>
</form>
<script>
function previewFile() {
var file = document.querySelector('input[type=file]').files[0];
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
if (file) {
ctx.drawImage(file,385,345);
}
}
</script>
</body>
</html>
I believe this to be a duplicate, as mentioned in my comment.
But just out of curiosity, I built a working example below.
You must wait until the image loads before checking its dimensions.
function checkData() {
console.log('checking image size...');
var img = new Image();
var images = document.getElementsByName('img');
var ctx = document.getElementById('canvas').getContext('2d');
img.onload = function() {
if (img.width != 385 || img.height != 345) {
console.log("Wrong size: " + img.width + " X " + img.height);
} else {
ctx.drawImage(this, 20, 20);
console.log("The image is drawn.");
}
}
img.onerror = function(e) {
console.log("Not ok", e);
}
img.src = URL.createObjectURL(images[0].files[0]);
}
var myform = document.getElementById('myform');
myform.addEventListener('submit', function(e) {
e.preventDefault();
checkData();
});
#canvas {
width: 20px;
height: 20px;
}
<form method="post" name="form" id="myform" action="">
Image 1
<input type="file" name="img"><br>
<input type="submit" value="check">
</form>
<canvas id="canvas"></canvas>

ajax image upload with pre-preview

I am uploading image with ajax and showing image before uploading with jquery.
here is my html code
<form id="uploadimageS2" action="" method="post" enctype="multipart/form-data">
<div id="image_previewS2"><img id="previewingS2" src="img/noimage.png" /></div>
<div id="selectImageS2">
<label>Select Your Image</label><br/>
<input type="file" name="fileS2" id="fileS2" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
then here is my jquery code
// Function to preview image
$("#fileS2").change(function() {
$("#messageS2").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewingS2').attr('src','img/noimage.png');
$("#messageS2").html("<p id='errormsg'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
function imageIsLoaded(e) {
$('#image_previewS2').css("display", "block");
$('#previewingS2').attr('src', e.target.result);
$('#previewingS2').attr('width', '250px');
$('#previewingS2').attr('height', '230px');
};
reader.readAsDataURL(this.files[0]);
var file = this.files[0];
here i want to add another element instead of "this". because i am uploading 3 images in one page and when using this script it is going wired.
i already tried
reader.readAsDataURL($(#uploadimageS2).files[0]);
reader.readAsDataURL($(#fileS2).files[0]);
and those didn't work.

jQuery Multiple File Upload Plugin check wheather empty or not

I have downloaded JQuery Multiple file uploader from this site
http://www.fyneworks.com/jquery/multiple-file-upload/
I need to check whether the file input field is null or not before submitting the form.
<form onsubmit="return validate();">
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="submit" name="BtnSubmit" value="save" />
</form>
I tried
function validate() {
$(".multi").each(function () {
var multi = $(this).val();
if (multi) {
return true;
} else {
return false;
}
});
}
Not working because the filed is always empty. So is there any other way to achieve this ?
try this
var multi = $(".multi").val();
if (multi) {
console.log("multi");
} else {
console.log("no multi");
}
fiddle:
http://jsfiddle.net/w4qVv/
UPDATE:
or you can do it like this
function validate(field) {
var fieldVal = $(field).val();
if(!fieldVal) alert("No files selected");
}
and then:
validate(".multi");
fiddle:
http://jsfiddle.net/jk8aZ/
UPDATE2:
yep, you can use each like this
var multi = (".multi");
$(multi).each(function () {
validate(this);
});
fiddle:
http://jsfiddle.net/jk8aZ/1/

File type validation!! for generated input file tag elements

JSP:
----
<div ID="items">
input id="file5" type="file" path="files" name="files" size="40" /> Other documents
</div>
Javascript:
-----------
<script type="text/javascript">
var items=1;
function AddItem() {
var div=document.getElementById("items");
var button=document.getElementById("add");
items++;
newitem="";
newitem+="<input type=\"file\" path=\"files\" name=\"files\"";// + items;
newitem+="\"id=file"+items;
newitem+="\" size=\"40\"> Other documents";
newitem+=" <input type=\"button\" class=\"button\" id=\"delButton"+items;
newitem+="\" value=\"\" name=\"button"+items;
newitem+="\" onclick=deletethisRow("+items+")>";
newnode=document.createElement("div");
newnode.setAttribute("id","child"+items);
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
}
function deletethisRow(obj){
var fileElement=document.getElementById("file"+obj);
var buttonElement=document.getElementById("delButton"+obj);
var childDivName="child"+obj;
if (buttonElement) {
var child = document.getElementById(childDivName);
var parent = document.getElementById("items");
parent.removeChild(child);
}
}
</script>
---
Above is the JSP code as well as JavaScript snippets.. I'm trying to validate the input files....
I want to allow only jpg,png,pdf,doc,docx file types to be upload??
Any thoughts on how to achieve this?
Thanks and regards,
Satish Krishnamurthy
You can change your input tag:
<input type="file" name="pic" id="pic" accept=".someext, image/gif, image/jpeg" />
But please don't rely on client-side validation. Check it server-side or people can disable the client-side checks and upload even executable scripts.
function Checkfilesextension()
{
var fileToupload = document.getElementById('elementId');
var fileName = fileToupload .value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
ext.toLowerCase
if(ext =="GIF" || other extension) // add other extensions
{
return true;
}
else
{
alert("Upload only the allowed files");
return false;
}
}
This would check for the extension of the files....have not tested the code though

Categories

Resources