Jump to content

input type file onchange


joymis

Recommended Posts

Hello,

 

I have a javascript code like this

<input type="file" class="filename" onchange="myFunction(this)">

<script>
function myFunction(elem) {
    if(elem.value.replace(/C:\\fakepath\\/g ,"").length > 20)
    {
	elem.value = elem.defaultValue;
	alert('The file name too long!');
	return false;
    }
    else{
         alert('OK');
    }
}
</script>

when I select a file, the IE11 will display two message, fisrt alert 'ok' then alert 'The file name too long!'

 

but firefox and chrome is correct, only display 'The file name too long!'

 

how can I do that IE11 only display one message?

 

Thanks.

Edited by joymis
Link to comment
Share on other sites

The trouble is also different browser show path differently Chrome 'fakepath', with some remove or keeping path so your if condition can't cover them all and you have larger problem if they change it further in future. The best alternative is to retrieve just the filename whatever path is used because that should never change, so using formula from http://stackoverflow.com/questions/857618/javascript-how-to-extract-filename-from-a-file-input-control

                            function myFunction(elem) {

                                var fullPath = elem.value;
                                if (fullPath) {
                                    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
                                    var filename = fullPath.substring(startIndex);
                                    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
                                        filename = filename.substring(1);
                                    }

                                }


                                if (filename.length > 20)
                                {
                                    alert("The file name too long! :" + elem.value + " : " + elem.value.length)

                                    elem.value = elem.defaultValue;
                                    //alert('The file name too long!');
                                    return false;
                                }
                                else {
                                    alert("OK :" + elem.value + " : " + elem.value.length)
                                    //alert('OK');
                                }
                            }

I left in alert message to show the different total lengths because of different paths used for different browsers.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...