I have a form with <input type="file">
. It has display:none, so to style it I’m using a label. Every required input in the form has a "required" class. When it’s empty the form won’t be sent and there is a red border around the empty input. The problem is that when I’m trying to validate my form ("required" class is on the label since input file has display:none) and the form validation reads it like it’s always empty (no matter if I upload a file or not).
// head
<script>
$(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
let sendForm = true;
$('.required').each(function(){
if ($(this).val() == ''){
$('#add').addClass('error');
$(this).addClass('error');
sendForm = false;
} else {
$(this).removeClass('error');
}
})
if (sendForm) {
$.ajax({
type: "post",
url: 'php/php.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function () {
document.getElementById("text").innerHTML = "success";
document.getElementById("add").style.border = "2px solid green";
$("#add").fadeOut(3000);
},
error: function () {
document.getElementById("text").innerHTML = "error";
document.getElementById("add").style.border = "2px solid red";
}
});
}
});
});
</script>
<form id="form" method="POST" action="php/php.php" enctype="multipart/form-data".>
<input type="text" name="Name" id="name" class="required"><br>
Image (jpg, png):
<label for="upload_image" id="file_style" class="required">File</label>
<input type="file" style="display:none;" id="upload_image" name="Image" accept="image/*" onchange="loadFile(event)">
<br>
<img id="output">
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src)
}
};
</script>
<input type="number" name="Ing1" class="required">
<input type="text" name="Ing2" class="required"><br>
<input type="submit" name="Add" id="add">
</form>
.error{
border: solid 12px red;
}
(This is only a minimal working example, there is more code. That’s why there are "useless" functions.)
How can I make it so if the file is uploaded the validation script doesn’t see it as undefined?
2
Answers
I think I found the solution. I added this code:
into my submit function. I will need to change a few things to suit my needs, but it works as it should. Thank you all for the help and ideas how to fix it!
First, you don’t have a function called "loadFile", I’m not sure if you need it.
Second, in the
$('.required').each
, you loop throwlabels
, you need to get theinput
that associated with that label, so one solution is to get it byid
after gettingfor
attribute of the label, then check if there arefiles
in the input file, byinput.files.length
.