I’m trying to validate the input file field if it is empty or not but its not working.
I’m having multiple form tags on my page so i need to check if the current submitted form’s file input is empty or not.
$(document).ready(function() {
$("form").on('submit', function(e) {
e.preventDefault();
var fileInput = $(this).find('input[type="file"]');
console.log(fileInput);
if (fileInput.length === 0) {
alert("Please select a file to upload.");
return;
}
});
});
html
<div id="content">
<div style="padding:1% 0">
<table>
<thead>
<tr>
<td>Type</td>
<td>Select Files</td>
</tr>
</thead>
<tbody>
<tr>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="recID" value="">
<td>File 1</td>
<td><input type="file" name="file1" class="fileinput"></td>
<td><input type="submit" name="submit" value="Upload"></td>
</form>
</tr>
<tr>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="recID" value="">
<td>File 2</td>
<td><input type="file" name="file2" class="fileinput"></td>
<td><input type="submit" name="submit" value="Upload"></td>
</form>
</tr>
<tr>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="recID" value="">
<td>File 3</td>
<td><input type="file" name="file3" class="fileinput"></td>
<td><input type="submit" name="submit" value="Upload"></td>
</form>
</tr>
<tr>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="recID" value="">
<td>File 4</td>
<td><input type="file" name="file4" class="fileinput"></td>
<td><input type="submit" name="submit" value="Upload"></td>
</form>
</tr>
<tr></tr>
<tr><td colspan="3"><a href="back.php"><button type="button">Go Back</button></a></td></tr>
</tbody>
</table>
</div>
I tried multiple time by all methods but not working.
3
Answers
Make sure that you are not used form inside another form. it will conflict when place a form inside another form.
Value for files can be accessed under
.files
. You need to rectify the condition to check the length as below,Update:
In case of multiple forms where input type file is missing, it will throw undefined error. To resolve that add a check
typeof(fileInput[0]) !== "undefined"
in the condition.Check the value as below
@Updated as per the modified question. You need to restructure HTML table