0

I have a html table that lists data from data from a database. One of the entries is the file size in bytes. I want to display the value in the appropriate kb/mb/gb values.
I found a script here to make the conversion.

Below is my attempt at implementing the script, however it is not working.

The desired end state is to have a value like 3597671 Bytes display as 3.43 MB.

<script>
    function SizeSuffix(a, b = 2, k = 1024) { with (Math) { let d = floor(log(a) / log(k)); return 0 == a ? "0 Bytes" : parseFloat((a / pow(k, d)).toFixed(max(0, b))) + " " + ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"][d] } }
    function setSize(size, id) {
        document.getElementById(id).innerText = SizeSuffix(size);
    }
    window.onload = function () {
        var sizedata = document.getElementsByName("Size");
        for (size in sizedata) {
            bytes = size.innerText;
            setSize(bytes, size.id);
        }
    }
</script>
    @foreach (var History in Model)
    {
        <tr>
            <td>@History.Date</td>
            <td>@History.Path</td>
            <td>@History.File</td>
            <td name="Size" id="@History.Id">@History.FileSize</td>
        </tr>

    }

EDIT: I came up with a different solution. I am working with a partial view in razor pages. What I've done is pass the page model of the page that calls the partial view. I included a function in that page model that performs the transformation.
I replaced the line

<td name="Size" id="@History.Id">@History.FileSize</td>

with

<td>@Model.SizeSuffix((ulong)History.FileSize)</td>

and removed the script block. This performs the calculation when ever the partial view is loaded and supports the infinite scrolling code.

kg123
  • 11
  • 6
  • You need `of` instead of `in`. With `in`, size is the index, not the element itself. Also not sure what the point of the setSize function is supposed to be, you already have the element. All you need inside the loop is `size.innerText = SizeSuffix(size.innerText)` –  Mar 10 '22 at 21:40
  • perfect! thanks. That did the trick. I also removed the extra setSize function. – kg123 Mar 10 '22 at 22:02
  • I have a follow up question. My page also includes an [infinite scrolling feature](https://www.jerriepelser.com/blog/htmx-infinite-scrolling). The above function works great for the first set that's loaded, but anything that follows does not get converted. Is there any way to call the function from the element itself? instead of relying on the window.onload? – kg123 Mar 10 '22 at 22:22
  • You can't call something from HTML elements. You need to add to the code that appends the s so that it fixes the sizes after the insertion. The alternative of course is to convert the SizeSuffix function to PHP and do all this server-side. –  Mar 10 '22 at 22:57

0 Answers0