不更改html文本框输入

时间:2015-02-05 06:50:24

标签: javascript jquery html5

我正在使用具有css属性<input type="file">的{​​{1}}从文件资源管理器中选择一个文件,但我点击display:none标记会触发<a>。我的HTML和JavaScript:

<input type="file">

我在尝试做的是,如果我点击<!DOCTYPE html> <html> <head> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> function BrowseFile() { $('.attachmentlabel').val('spooky'); $('#file-01').click(); var filePath = $('#file-01').val().split('\\'), fileName = filePath[filePath.length - 1]; if (fileName !== '' && fileName !== undefined) { $('.attachmentlabel').val(fileName); } } </script> </head> <body> <input type="file" class="hidden-attachment" id='file-01'> @*the hidden field*@ <input type="text" name="Attachment" class="attachmentlabel"> @*here I want to show the file name*@ <a class="btn attachmnentbtn browse" onclick="BrowseFile()">Browse</a> </body> </html> ,它会调用<a>,此方法会触发BrowseFile()上的点击事件

我尝试了上面的代码,但这并没有改变<input type="file" class="hidden-attachment">的文本内容。我该如何解决这个问题以及

的原因是什么?

2 个答案:

答案 0 :(得分:1)

添加此代码:

$(document).ready(function(){
     $("#file-01").change(function () {
          $('.attachmentlabel').val($(this).val())
     });
});

您只需处理文件控件的更改事件,并在文本框中更新它。

检查以下代码

var repassword = "hello";
var password = "hello";

repassword = "hello1";
password = "hello";


function BrowseFile() {
                $('.attachmentlabel').val('spooky');
                $('#file-01').click();

                var filePath = $('#file-01').val().split('\\'),
                    fileName = filePath[filePath.length - 1];

                if (fileName !== '' && fileName !== undefined) {
                    
                    $('.attachmentlabel').val(fileName);
                }
            }

$(document).ready(function(){

$("#file-01").change(function () {
     $('.attachmentlabel').val($(this).val())
});
});
.hidden-attachment
{
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" class="hidden-attachment" id='file-01'><br>
    <input type="text" name="Attachment" class="attachmentlabel"><br>
     <a  class="btn attachmnentbtn browse" onclick="BrowseFile()">Browse</a>

答案 1 :(得分:0)

function BrowseFile() {
      $('#file-01').click();
                $('.attachmentlabel').val('spooky');
                $('#file-01').click();

                var filePath = $('#file-01').val().split('\\');
                    fileName = filePath[filePath.length - 1];

                if (fileName !== '' && fileName !== undefined) {

                    $('.attachmentlabel').val(fileName);
                }
    // Add this code in your function
   $('.hidden-attachment').change(function(){    
         var filename = $(this).val();
         $('.attachmentlabel').val(filename);
     });
}

<强> Demo