Why inline <script> tag doesn't show the value?

Viewed 293

ScreenI need to convert value received by the server (bytes to MB). Only option I have is to embed script tag and run the jquery function that converts that value. Problem is that inline script doesn't return any value to html.

function formatFileSize(bytes) {
    if (bytes == 0) return '0 Byte';
    return (bytes / Math.pow(1024, 2)).toFixed(2);
 }

Html code

 <td>
    <script>
         formatFileSize(DailyUsage.UsageVolume)
    </script>
</td>
3 Answers

Because nothing is outputting it to the token stream. All your function does is return the value, but nothing makes use of the value it returns.

You could output it using document.write, which will insert that output betweeen the <td> and </td> when the page is loaded:

<td>
    <script>
         document.write(formatFileSize(DailyUsage.UsageVolume))
    </script>
</td>

...but usually there are better approaches to outputting information than putting lots of inline script tags with document.write in them, and note that you'd have to have an in-scope variable called DailyUsage referencing an object with a UsageVolume property for that to work.

Try this:

<div id="result"></div> <script>
window.onload = function () {
    document.getElementById("result").innerHtml = formatFileSize(DailyUsage.UsageVolume);
}
</script>

You firstly need to have a html element and then to point the result of the function to this HTML

You can do as follows

<td id="content">
</td>


 <script>
     function formatFileSize(bytes) {
       if (bytes == 0) return '0 Byte';
          return (bytes / Math.pow(1024, 2)).toFixed(2);
      }
     document.getElementById("content").innerHTML = formatFileSize(DailyUsage.UsageVolume);
 </script>
Related