将值插入输入/ JavaScript

时间:2013-07-13 14:53:41

标签: javascript html dom javascript-events input

我有以下JS / HTML代码:

<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>

我希望在上传文件后,文件名将显示在tput文本中,但此文件不起作用。

我该如何解决?

更新:文件名应位于输入文本

3 个答案:

答案 0 :(得分:2)

script元素移到input元素之前。您最好将script元素放在head这样的

Demo

更新答案!

答案 1 :(得分:0)

您可以尝试以下代码:

<!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>

答案 2 :(得分:-2)

这样做:

HTML

<div class="file_upload">
    <input type="file" id="file_upload">
</div>
<div id="file_info"></div>

JS

function name(file) {
    var reader = new FileReader();
    reader.readAsText(file);

    reader.onload = function (event) {
        document.getElementById('file_info').innerHTML = "Filename: " + file.name + "\nContent: " + event.target.result;
    };

    reader.onerror = function () {
        alert('Unable to read ' + file.name);
    };
}

document.getElementById('file_upload').onchange = function () {
    name(this.files[0]);
};

DEMO