alternate to onchange event in <input type='file' />

前端 未结 8 1936
青春惊慌失措
青春惊慌失措 2020-12-10 04:04

Seems really a simple thing but can\'t figure it out. I\'ve been using the onchange event on element and it works well. Once the user browses and selects a file, I get the

相关标签:
8条回答
  • 2020-12-10 04:19
    function resetFileInput ($element) {
      var clone = $element.clone(false, false);
      $element.replaceWith(clone);
    }
    

    And then use live:

    $('#element_id').live('change', function(){
    ...
    });
    

    Worked well for me!

    0 讨论(0)
  • 2020-12-10 04:21

    Set the value of the input to "" in your onchange callback. That way, if the same file is selected the next time around, the onchange event will still be triggered because the value is different than "".

    document.getElementById('files').value = "";
    
    0 讨论(0)
  • 2020-12-10 04:25

    You can just remove the input and create an identical one with javascript - the new one will be empty.

    (edited answer to be straight to the point, comments are irrelevant now)

    0 讨论(0)
  • 2020-12-10 04:25

    There really isn't any way to fix that. If you add any other listener or timer, then you will potentially upload the file even when the user doesn't want it to (eg, with an onclick). Are you sure uploading the same file can't be done in another way? What about clearing the input once the upload has started (or replace it with a new input if you can't clear it).

    0 讨论(0)
  • 2020-12-10 04:29

    If you don't want to use jQuery

    <form enctype='multipart/form-data'>
        <input onchange="alert(this.value); return false;" type='file'>
        <br>
        <input type='submit' value='Upload'>
    </form>
    

    It works fine in Firefox, but for Chrome you need to add this.value=null; after alert.

    0 讨论(0)
  • 2020-12-10 04:30

    Is this behavior only present in IE? If so, it may be related to this issue:
    jQuery change event on <select> not firing in IE
    In essence: You may need to check for onClick instead.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题