简体   繁体   中英

onChange Input with Javascript

I have this code:

<input type="file" onchange="showUrl(this.value)" name="upload[]" multiple="multiple">
    <button type="button" class="btn btn-success"><i class="icon icon-plus"></i> Add file</button></span>
    <input type="submit" class="btn btn-primary" value="Upload"><br><br><span id="url"></span>

and this javascript function

function showUrl(url) {
   document.getElementById("url").innerHTML = url;
}

I want to show the url of every file that the user selects with "input file" button. The function shows only the url of the first file. Someone can help me? Thanks

First, change your input to:

<input type="file" onchange="showUrl(this)" name="upload[]" multiple="multiple">

Then, change your JS to:

function showUrl(url) { 
  for(var i = 0; i < url.files.length; i++) { 
    document.getElementById("url").innerHTML += url.files[i].name; 
  } 
}

That way you will be able to read all files selected on the files input.

I don't think you can get the full path, but you can get the file's name by passing this.files instead of this.value

function showUrl(url) {
   for(var i = 0; i < url.length; i++)
   {
       document.getElementById("url").innerHTML += url[i].name + "<br>";
   }
}

Javascript

<script type="text/javascript">
function showUrl() {
    var allFiles = document.getElementById("myFiles");

    if ('files' in allFiles) {
        if (allFiles.files.length > 0) {
            for (var i = 0; i < allFiles.files.length; i++) {
                document.getElementById("url").innerHTML += "<br />"+allFiles.files[i].name;
// note you can mess with proprieties here, like 'size'
            }
        }
    }
}
</script>

HTML

<body>
    <input type="file" onchange="showUrl()" name="upload[]" id="myFiles" multiple="multiple">
    <button type="button" class="btn btn-success"><i class="icon icon-plus"></i> Add file</button></span>
    <input type="submit" class="btn btn-primary" value="Upload">
    <br /><br />
    <span id="url"></span>
</body>

I'm not sure of what you're after. try:

function showUrl(url) {
   document.getElementById("url").innerHTML += url;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM