Adeeb Keyaam
Adeeb Keyaam

Reputation: 21

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

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

Upvotes: 0

Views: 244

Answers (5)

itz2k13
itz2k13

Reputation: 159

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>

Upvotes: 0

F__M
F__M

Reputation: 1598

Try:

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

or

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


Why .val?

Form 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. In the case of elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.

Upvotes: 0

Dmitrii Tarasov
Dmitrii Tarasov

Reputation: 414

Use "val" instead of "append"

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

Upvotes: 1

Patrick Kostjens
Patrick Kostjens

Reputation: 5105

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.

Upvotes: 1

PSR
PSR

Reputation: 40318

when i want to show it as input value. use .val() ..append() will not work for input .

Upvotes: 0

Related Questions