-1

I can get the file name from file upload to the textarea in IE and Chrome. But it not work on firefox, how can i solve this problem?

Many Thanks.

        function takeName(event) {
            let filename = event.path[0].files[0].name;
            document.getElementById("txtComment").value = filename;
        }
  
<form id="Apply" name="Apply" method="post" enctype="multipart/form-data" action="applyLeave.php">
    Get upload filename to textarea:
    <p><textarea rows="3" cols="30" name="txtComment" id="txtComment" class="valid"></textarea></p>
    <p>Select image to upload: <input type="file" onchange="takeName(event)" name="fileToUpload" id="fileToUpload"></p>
    <p><input type="submit" value="Submit" name="submit"></p>
</form>
zer00ne
  • 36,692
  • 5
  • 39
  • 58
tea
  • 11
  • 2
  • 1
    What's the problem? How do you know it doesn't work on Firefox? – Spectric Apr 30 '21 at 02:32
  • Well I use Firefox and `document.getElementById` posted works just fine. – ikiK Apr 30 '21 at 02:38
  • Your code conflates multiple possibilities, so step 1 is to split it up. `let element = event.path[0]; let file = element.files[0]; let name = file.name; let comment = document.getElementById("txtComment"); comment.value = filename;` and then you'll first notice that you wanted `event.target`, not `event.path[0]` and then you'll notice this had nothing to do with `document.getElementById` and you jumped to conclusions rather than verifying your assumptions. Always good to get extra verbose when you're debugging. You can always collapse it again once things work. – Mike 'Pomax' Kamermans Apr 30 '21 at 02:43

2 Answers2

2

document.getElementById() compatibility with any browser is unquestionable that isn't the problem. See this answer about .path compatibility with Firefox.

Replace event.path[0] with event.target.

function takeName(event) {
  let filename = event.target.files[0].name;
  document.getElementById("txtComment").value = filename;
}
<form id="Apply" name="Apply" method="post" enctype="multipart/form-data" action="applyLeave.php">
  Get upload filename to textarea:
  <p><textarea rows="3" cols="30" name="txtComment" id="txtComment" class="valid"></textarea></p>
  <p>Select image to upload: <input type="file" onchange="takeName(event)" name="fileToUpload" id="fileToUpload"></p>
  <p><input type="submit" value="Submit" name="submit"></p>
</form>
zer00ne
  • 36,692
  • 5
  • 39
  • 58
0

When I use in firefox that show event.path is undefined, I suggest you use event.target.files to get file name