javascript - 不改变html文本框输入

标签 javascript jquery html

我正在使用 <input type="file"> 从文件资源管理器中选择文件其具有 css 属性 display:none但我点击<a>标签将触发 <input type="file"> 。下面是我的 HTML 和 JavaScript:

<!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">上的点击事件

我尝试了上面的代码,但这并没有改变 <input type='text'> 的文本内容。我该如何解决这个问题以及原因是什么

最佳答案

添加此代码:

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

关于javascript - 不改变html文本框输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337812/

相关文章:

javascript - 将弹出框放在 noUiSlider handle 上

javascript - HTML5 Canvas - 从左上角绘制圆圈

javascript - 如何更改对象中特定值的字体颜色?

javascript - Chrome 应用程序在全屏中创建新窗口 - html 元素不是全高

jquery - 页面宽的面包屑栏,如 apple.com/store

javascript - 使用 Kendo UI 折线图,如何保持条形点连接? (见图)

javascript - Safari 不显示 Div

html - 我的段落不会上下移动;

javascript - 如果我在 javascript 中子类化时没有正确设置构造函数,会出现什么问题?

javascript - 通过 Firebase auth() 管理其他用户帐户