HTML <input type='file'> File Selection Event

南楼画角 提交于 2019-12-17 17:27:15

问题


Let's say we have this code:

<form action='' method='POST' enctype='multipart/form-data'>
    <input type='file' name='userFile'><br>
    <input type='submit' name='upload_btn' value='upload'>
</form>

which results in this:

When the user clicks the 'Browse...' button, a file search dialog box is opened:

The user will select the file either by double-clicking the file or by clicking the 'Open' button .

Is there a Javascript Event that I can use to be notified after after the file is selected?


回答1:


Listen to the change event.

input.onchange = function(e) { 
  ..
};



回答2:


When you have to reload the file, you can erase the value of input. Next time you add a file, 'on change' event will trigger.

document.getElementById('my_input').value = null;
// ^ that just erase the file path but do the trick



回答3:


jQuery way:

$('input[name=myInputName]').change(function(ev) {

    // your code
});



回答4:


The Change event gets called even if you click on cancel..




回答5:


That's the way I did it with pure JS:

var files = document.getElementById('filePoster');
var submit = document.getElementById('submitFiles');
var warning = document.getElementById('warning');
files.addEventListener("change", function () {
  if (files.files.length > 10) {
    submit.disabled = true;
    warning.classList += "warn"
    return;
  }
  submit.disabled = false;
});
#warning {
    text-align: center;
}

#warning.warn {
	color: red;
	transform: scale(1.5);
	transition: 1s all;
}
<section id="shortcode-5" class="shortcode-5 pb-50">
    <p id="warning">Please do not upload more than 10 images at once.</p>
    <form class="imagePoster" enctype="multipart/form-data" action="/gallery/imagePoster" method="post">
        <div class="input-group">
  	    <input id="filePoster" type="file" class="form-control" name="photo" required="required" multiple="multiple" />
	    <button id="submitFiles" class="btn btn-primary" type="submit" name="button">Submit</button>
        </div>
    </form>
</section>


来源:https://stackoverflow.com/questions/3528359/html-input-type-file-file-selection-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!