user_1330
user_1330

Reputation: 504

The extension of a file with JS HTML

I want to test the extension of a given file

JS

function get_extension(file_name) {
    return file_name.split('.').pop();
}

function check_file_type(file) { 

    switch(get_extension(file)) {
        case 'jpg': case 'gif': case 'png':
            var element = document.getElementById('p');
            element.innerHTML = "Je suis une image";
            break;

        case 'mp4' :
            var element = document.getElementById('p');
            element.innerHTML = "Je suis une video";

    }
}

HTML

   <button onclick="check_file_type(<%=(chemin_photo1)%>)">Click me!</button> 
   <p id="p"></p>

But it will show nothing, thank you in advance

Upvotes: 1

Views: 72

Answers (2)

i100
i100

Reputation: 4666

You should consider a few things here. First what comes from the server. As @Frederico suggested, it must be quoted as it is supposed to be a file name (string)

<button onclick="check_file_type('<%=(chemin_photo1)%>')">Click me!</button>

Next, you must always check what the value of the argument passed is. It should be at the beginning of the function or as a default in your case block because even if you have quoted the server output it could still be an empty string ('') and in your case, it'd seem not working.

function check_file_type(file) { 

    var element = document.getElementById('p');

    switch(get_extension(file)) {
        case 'jpg': case 'gif': case 'png':
            element.innerHTML = "Je suis une image";
            break;

        case 'mp4' :
            element.innerHTML = "Je suis une video";
            break;

        default:
            element.innerHTML = "oh-la-la!";
            break;
    }
}

Upvotes: 2

Federico klez Culloca
Federico klez Culloca

Reputation: 27139

I suppose chemin_photo1 is a string, not the name of a global variable, so you'll need to wrap it in quotes

<button onclick="check_file_type('<%=(chemin_photo1)%>')">Click me!</button>

Upvotes: 2

Related Questions