I want to alert that "Please enter file .docx and .pdf" so I need the extension of the file...
$(".upload").click(function () {
var filename = $("#file").val();
var extension = " ";
})
Here you have a working example. Just use .split()
on the provided path
$(".upload").click(function () {
var filename = $("#file").val();
var pathParts = filename.split('/'); // Split the path on '/': ['path', 'to', 'file.ext']
var filename = pathParts.pop(); // Take the last element. This is a file name: 'file.ext'
var filenameParts filename.split('.'); // Split the file name on the '.': ['file', 'ext']
var extension = filenameParts[1]; // Take the extension: 'ext'
});
Or you can do it in one line:
var extension = filename.split('/').pop().split('.')[1];
Using the Split function
$("#file").val('file.ext');
$("#upload").click(function () {
var filename = $("#file").val();
var aux = filename.split('.');
var extension = aux[aux.length -1].toUpperCase();
if(extension === 'DOC'
|| extension === 'DOCX'
|| extension === 'PDF'
){
alert('Valid extension.');
}else{
alert('Invalid extension: ' + extension + '. Only: DOC, DOCX, PDF are allowed.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='file'/>
<button id='upload'>Upload</button>