Search code examples
jqueryasp.netverification

Launching jQuery method using Asp.Net control


I try to launch a jQuery method when I select a file from FileUpload control in Asp.Net but it does not work. The jQuery method has to check the file size that is selected. How can I fix this?

<script type="text/javascript">
    function ValidateUploadButton() {
        //this code will be executed when a new file is selected
        $('#FileUpload1').bind('change', function () {
            //converts the file size from bytes to MB 
            var fileSize = this.files[0].size / 1024;

            //checks whether the file is less than 1 MB 
            if (fileSize > 1) {
                $('#errorMessage').html("The file is too big")
                alert("okey");
                //successfully validated 
            }
            else {
                alert("else");
            }
        });
    }
</script>

 

<asp:FileUpload ID="FileUpload1" runat="server" ClientValidationFunction="ValidateUploadButton" />
<span id="errorMessage"></span>

Solution

  • I changed your ClientValidationFunction attribute to onchange.

    <asp:FileUpload ID="FileUpload1" runat="server" onchange="ValidateUploadButton();" />
    <span id="errorMessage"></span>
    

    Edited the script to remove the 'change' bind since now ValidateUploadButton is called because of the change.

    <script type="text/javascript">
    function ValidateUploadButton()
    {
        //this code will be executed when a new file is selected
        //converts the file size from bytes to Ko 
        var fileSize = $('#FileUpload1')[0].files[0].size / 1024 / 1024;
        // USE THIS BELOW IF THE ONE ABOVE DOESN'T WORK
        //var fileSize = $('#<%= FileUpload1.ClientID %>')[0].files[0].size / 1024 / 1024;
    
        //checks whether the file is less than 1 MB 
        if (fileSize > 1)
        {
            $('#errorMessage').html("The file is too big")
            alert("okey");
            //successfully validated 
        }
        else
        {
            alert("else");
        }
    }
    </script>
    

    EDIT

    Sorry I failed to test this thoroughly. It should work now. The javascript syntax of properly referencing the filesize was wrong. Also I added an extra division of 1024 so you will get it in MB instead of KB.

    Note - This only works on one file, not supported for multiple files.