Tom Odell Tom Odell - 6 months ago 20
Javascript Question

Checking file extension with JQUERY is not working

I have got this jquery

$("#Nameupload").change(function(e) {
if ($(this).val()!="") {
$(".PhotShow").slideDown(500,function(){
$('html, body').animate({ scrollTop: 1000}, 900);
});
var filename = $(this).val();
var extension = filename.replace(/^.*\./, '');
if (extension == filename) {
extension = '';
} else {
extension = extension.toLowerCase();
}
if (extension!="png" || extension!="jpg" ) {
$(".PhotShow").html("Some text and markup");
}
readURL(this);
}
});


So what i am trying to do here is check file's extension,but even when i put

alert(extension);


it returns "jpg"
But still this code is working

$(".PhotShow").html("Some text and markup");


What may be the problem?

Answer

The problem is your logic in the if statement. If the text isn't png and it isn't jpg then your condition will always be hit as at least one of those statements is always true. Change your logic condition to an &&:

if (extension != "png" && extension != "jpg") {
    $(".PhotShow").html("Some text and markup");
}

Also note that your code can be cleaned up slightly with regard to validating that a filename exists (it always will in the change event) so your if condition checking the value can be removed. Also note that you can split() the value by . and pop() the last element of the array as a tidier way of getting the extension. Try this:

$("#Nameupload").change(function(e) {
    $(".PhotShow").slideDown(500, function() {
        $('html, body').animate({
            scrollTop: 1000
        }, 900);
    });

    var extension = $(this).val().split('.').pop().toLowerCase();
    if (extension != "png" && extension != "jpg") {
        $(".PhotShow").html("Some text and markup");
    } else {       
        readURL(this);
    }
});
Comments