3
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <style type="text/css">
        #filee{
            visibility: hidden;
        }
    </style>
</head>
<body>
    <input type="file" name="" id="filee">
    <button onclick= "ftn()" id="btn">Choose a File</button>
    <span id="filename"></span> 
    <script type="text/javascript">
        let file = document.getElementById('filee');
        let btn = document.getElementById("btn");
        let filename = document.getElementById("filename");
        function ftn(){
            file.click();
            let value = file.value;
            filename.innerText = value;
        }

    </script>
</body>
</html>

This is my code. I'm getting value when i clicked button 2nd time. I want a value in span tag of my file when i click on button and open it. This giving value when i clicked again a button and show me previous value of file. Thanks if you get my point

  • The code does as it should, but probably not as you want. `ftn()` clicks the file input (which opens the dialog) but `let value = file.value` is set **immediately**. which is empty. Only the second time a value exists. – agoldev Jul 18 '22 at 22:01

1 Answers1

0

You'll want to know the name of the file whenever you've uploaded it to the browser. That means that you have to listen for the change event on the file input.

let file = document.getElementById('filee');
let btn = document.getElementById("btn");
let filename = document.getElementById("filename");

file.addEventListener('change', event => {
  const [file] = event.target.files
  filename.innerText = file.name;
});

btn.addEventListener('click', () => {
  file.click();
});
#filee {
  clip: rect(0 0 0 0); 
  clip-path: inset(50%);
  height: 1px;
  overflow: hidden;
  position: absolute;
  white-space: nowrap; 
  width: 1px;
}
<input type="file" name="" id="filee">
<button type="button" id="btn">Choose a File</button>
<span id="filename"></span>
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32