简体   繁体   English

想要使用javascript / jquery在输入标签中显示文件上传大小

[英]want to show file upload size in input tag using javascript/jquery

In the code below, I want to show the size of uploaded file in a div or label element. 在下面的代码中,我想在div或label元素中显示上传文件的大小。 However, it doesn't work when I want to show it in an input element. 但是,当我想在输入元素中显示它时,它不起作用。

 <script>
    var maxfilesize = 2097152;//2MB;
    $('#fuAttachments').live("change", function () {
        $("#msg").text("");

        var tt = $(this).val();

        var size = this.files[0].size;
        $("#msg").append(Math.ceil(size / 1024));

    });
</script>
<input id="fuAttachments" type="file" />

I want to display the size of uploaded file in #msg 我想在#msg中显示上传文件的大小

<input id="msg" type="text" />

It should work when you replace this line: 替换此行时它应该工作:

$("#msg").append(Math.ceil(size / 1024));

With this: 有了这个:

$("#msg").val(Math.ceil(size / 1024));

The .val() function sets the value property of all matched tags, while the .append() function inserts content at the end of the element. .val()函数设置所有匹配标记的value属性,而.append()函数在元素末尾插入内容。

使用“val”而不是“append”

$('#msg').val(size);

when i want to show it as input value. 当我想将它显示为输入值时。 use .val() . 使用.val() .append() will not work for input . .append()不适用于输入。

Try: 尝试:

$("#msg").val(Math.ceil(size / 1024));

or 要么

$("#msg").val(size);


Why .val? 为什么.val?

Form jQuery Doc: 表单jQuery Doc:
Get the current value of the first element in the set of matched elements or set the value of every matched element. 获取匹配元素集中第一个元素的当前值或设置每个匹配元素的值。 The .val() method is primarily used to get the values of form elements such as input, select and textarea. .val()方法主要用于获取表单元素的值,例如input,select和textarea。 In the case of elements, the .val() method returns an array containing each selected option; 对于元素,.val()方法返回包含每个选定选项的数组; if no option is selected, it returns null. 如果未选择任何选项,则返回null。

Please use the following script: 请使用以下脚本:

<script>
 var maxfilesize = 2097152;//2MB;
 $('#fuAttachments').live("change", function () {
    var size = $(this).files[0].size;
    $("#msg").val(Math.ceil(size / 1024));

 });
</script>

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

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