Insert value to input / JavaScript

20,164

Solution 1

Move your script element before the input element. You had better put the script element inside your head like this

Demo

Have update the answer!

Solution 2

You can try this code:

<!DOCTYPE html>
<html>
    <head>
        <script>
            function myFunction()
            {
                var fileName =document.getElementById("file_upload").value;
                var fnSplit = fileName.split(/[\/\\]/);
                fileName = fnSplit[fnSplit.length - 1];

                document.getElementById('file_info').value = fileName
            }
        </script>
    </head>
    <body>

        <input type="text" class="file" name="file_info" id="file_info">
        <div class="file_upload">
            <input type="file" id="file_upload" onchange="myFunction();">
        </div>
    </body>
</html>
Share:
20,164
Nave Tseva
Author by

Nave Tseva

Updated on July 09, 2022

Comments

  • Nave Tseva
    Nave Tseva almost 2 years

    I have the following JS / HTML code:

    <input type="text" class="file" name="file_info" id="file_info">
        <div class="file_upload">
            <input type="file" id="file_upload" onchange="name();">
        </div>
    <script>
        function name() {
            var fileName = document.getElementById("file_upload").value;
            var fnSplit = fileName.split(/[\/\\]/);
            fileName = fnSplit[fnSplit.length - 1];
          document.getElementById('file_info').innerHTML = 'Fred Flinstone';
        }
    </script>
    

    I want that after I upload file, the file-name will shown in the tput text, but this cide doesn't work.

    How can I fix it?

    Update : The file name should be inside the input text

  • Brad Christie
    Brad Christie almost 11 years
    Input elements don't use innerHTML either. Probably want value.
  • Nave Tseva
    Nave Tseva almost 11 years
    The file name should be in sepreat input
  • Nave Tseva
    Nave Tseva almost 11 years
    The file name should be in sepreat input text
  • Hieu Le
    Hieu Le almost 11 years
    @Jonathan we can get the file path form file object element w3schools.com/jsref/dom_obj_fileupload.asp
  • Hieu Le
    Hieu Le almost 11 years
    @BradChristie sorry, thanks for your opinion, I have checked the code and fixed it.
  • Hieu Le
    Hieu Le almost 11 years
    @NaveTseva You can check it now, I just forget update the link, the current revision is 3.