2

If someone tries to upload a file with a non-allowed file-extension, this input-file-element should get "reseted".

That is the input-file-element

<input type="file" id="image1">

These are the corresponding jQuery-statements (document is ready) and I get "TypeError: myElement.clone is not a function" (while I am trying this solution here: Clearing <input type='file' /> using jQuery)

$(document).ready(function() {
    $('#image1').change(function(event) {
        checkExtensions(this.files[0].name, $(this).get());
    });

    function checkExtensions (fileName, element) {

        var myElement = element;
        var allowedExtensions = new Array ('pdf','gif','jpg','png');
        var currentExtension = fileName.split('.').pop();

        if ($.inArray (currentExtension, allowedExtensions) > -1) {
            // everythins is OK, further instructions take place
        }   else {
            // reset the file input element
            myElement.replaceWith( myElement = myElement.clone( true ) );
        }
    }
});
Community
  • 1
  • 1

1 Answers1

1

You are passing the native DOM element to your function instead of the jQuery object containing the element. Native DOM elements do not have the function clone() (or replaceWith either). Try this instead:

$('#image1').change(function(event) {
    checkExtensions(this.files[0].name, $(this)); // note, I removed .get()
});

function checkExtensions (fileName, $element) {
    var allowedExtensions = new Array ('pdf','gif','jpg','png');
    var currentExtension = fileName.split('.').pop();

    if ($.inArray (currentExtension, allowedExtensions) > -1) {
        // everything is OK, further instructions take place
    }   else {
        // reset the file input element        
        $element.replaceWith($element.clone(true).val(''));
    }
}

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339