0

In an MVC application, I'm having users upload a file and then doing some error handling. This portion works fine.

The file input is:

<div class="col-md-3" id="browsebutton">
                <label class="btn btn-primary btn-file">
                    Browse<input type="file" id="FileUpload" name="FileUpload" class="" />
                </label></div>

I want to display the file name as soon as a user chooses it, so I added this bit of JavaScript and an onChange="getFileName():

        function getFileName() {
            str = document.getElementById("FileUpload").value;
            var filename = str.substring(12, str.length);

            document.getElementById("browsebutton").innerHTML += filename;
        }
        var coll = document.getElementsByClassName("collapsible");
        var i;

This properly displays the filename. However, as soon as I add this, the FileUpload becomes null in my controller.

How is this JavaScript interfering with my file upload?

3
  • Is that the entirety of the getFileName handler? I don't see how it could interfere with anything. Commented Jan 21, 2019 at 14:31
  • Interestingly, if I create a separate div and inject the file name into that instead of appending to the same div as button, it works fine. Which is a workable solution for me! :) Commented Jan 21, 2019 at 14:50
  • Oh, I see it now. You're appending to the innerHtml, which reassigns the entire contents back to the div, resulting in a cleared input element. You can instead create a new element and append that element to browsebutton using DOM methods, instead of appending a string. Commented Jan 21, 2019 at 14:52

1 Answer 1

1

Replace this line:

document.getElementById("browsebutton").innerHTML += filename;

With:

var fnSpan = document.createElement("span");
fnSpan.innerText = filename;
document.getElementById("browsebutton").appendChild(fnSpan);

The way you're doing it, you're setting the contents of the innerHtml, which ends up clearing the input (the input's value isn't part of the innerHtml string). Use DOM manipulation methods instead.

You can also make the span a permanent part of the DOM, and simply set its innerText in your code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.