繁体   English   中英

更新JavaScript中的表单字段

[英]Update form field in JavaScript

我的网站上有一个用于上传图片的表格。 表单有效,但是Javascript并未按照我的期望运行。 我想要做的是使用“浏览”按钮选择图像时,使用文件名更新相邻的输入字段。 谁能看到为什么这行不通?

这是HTML:

<div class="input-group">
    <span class="input-group-btn">
        <span class="btn btn-danger btn-file">
            Browse… <input type="file" name="Image" multiple="">
        </span> 
    </span>
    <input type="text" class="form-control filename" readonly="">
</div>

这是Javascript:

<script type="text/javascript">
    $(document).on('change', '.btn-file :file', function() {
        var input = $('.filename'),
            numFiles = input.get(0).files ? input.get(0).files.length : 1,
            label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
        input.trigger('fileselect', [numFiles, label]);
    });
</script>

使用此代码将为您提供帮助

<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<style>
.btnEdit{display:none;}
</style>
</head>
<script type="text/javascript">
    $(document).on('change', '.btn-file :file', function() {
      var fileName = $('#uploadfile').val();
      $('.filename').val(fileName);
    });
</script>
<div class="input-group">
    <span class="input-group-btn">
        <span class="btn btn-danger btn-file">
            Browse… <input id = 'uploadfile' type="file" name="Image" multiple="">
        </span> 
    </span>
    <input type="text" class="form-control filename" readonly="">
</div>

希望这对您有用。

$(document).on('change', '.btn-file :file', function(value) {
console.log(value);
    var input = $('.filename'),
        numFiles = value.target.files ? value.target.files.length : 1,
        label = value.target.files[0].name.replace(/\\/g, '/').replace(/.*\//, '');
    input.val(label);
});

在该变量用于从元素中获取文件名之后,我在更改事件中添加了作为参数。

要进行测试,您可以从此处进行测试: http : //jsfiddle.net/u4od6b2L/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM