When working with an input type file, if an image is selected it will show a preview. If something other than an image, like a PDF or DOCX file, is selected I want to show an alert as invalid. However, I am encountering an error: Cannot read property 'split' of undefined
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<input type='file' id='input1'>
<div class="hide_this" style="display:none;"> <img id='imagepreview1' width="100" height="100" >
<button type="button" class="close" aria-label="Close" style="position: absolute;top:30px;opacity:1.2;">
<span aria-hidden="true" style="color:black;">×</span>
</button>
</div>
<script>
$("#input1").change(function() {
readURL(this);
$('#imagepreview1').show();
$('.hide_this').css({
'display': 'block'
});
});
$('.close').click(function() {
$(".hide_this").hide();
document.getElementById("input1").value = "";
$("#imagepreview1").hide();
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var ext = input.files[0].name.split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
alert('invalid extension!');
}
$('#imagepreview1').prop('src', e.target.result).show();
}
reader.readAsDataURL(input.files[0]);
}
}
</script>