Reputation: 303
var $imagefile = $('<input />')
.attr({
type: 'file',
name: 'imageFile',
id: 'imageFile'
});
Above is my code which creates a file input.
Below is the code which checks if a file format is correct in a table row:
function validation() {
var marks = parseInt($("#total-weight").text());
var _qid = "";
var _msg = "";
var allowedTypes = ["jpg", "jpeg", "gif", "png"];
var path = $("#imageFile").val();
var ext = path.substring(path.lastIndexOf('.') + 1).toLowerCase();
var alertValidation = "";
// Note, this is just so it's declared...
$("tr.optionAndAnswer").each(function() {
_qid = $("td.qid",this).text();
_msg = "You have errors on Question Number: " + _qid + "\n";
$("#imageFile",this).each(function() {
if ($.inArray(ext, allowedTypes) < 0) {
alertValidation += '\n\u2022 Unsupported file type';
}
if (alertValidation != "") {
return false; //Stop the each loop
}
});
if(alertValidation != ""){
return false;
}
});
if (alertValidation != "") {
alert(_msg + alertValidation);
return false;
}
return true;
}
Now this works fine by recognising which file type is correct and incorrect. The problem is though that if in all table rows the user does not select a file, then it comes up with the alert which is incorrect.
How can I get it so that it also allows a blank file input where the user does not select a file?
Upvotes: 0
Views: 562
Reputation: 1959
In this routine
$("#imageFile",this).each(function() {
if ($.inArray(ext, allowedTypes) < 0) {
alertValidation += '\n\u2022 Unsupported file type';
}
if (alertValidation != "") {
return false; //Stop the each loop
}
});
You should check to see if it has a value, and if so, continue processing. Something like this:
$("#imageFile",this).each(function() {
if($(this).val().length) {
// continue on
}
});
After our comments, you should probably be using a class selector instead of an id selector. So your creation code should probably look like:
var $imagefile = $('<input />')
.attr({
type: 'file',
name: 'imageFile',
class: 'imageFile'
});
And your routine should be:
$(".imageFile",this).each(...
That way you can iterate over a collection.
Upvotes: 1