Zal
Zal

Reputation: 975

Function returns nothing embedded in html, while working in console

I have the following function. It runs correctly in console, but does not return anything on my website.

(quite new to JS)

Console output:

>       function format_number_euro(number) {
...         let formatter = new Intl.NumberFormat('nl-NL', {style: 'currency', currency: 'EUR'})
...         return formatter.format(number)
...       }
undefined
> format_number_euro(25412)
'€ 25.412,00'

Way I am calling it in my web app:

  1. Defined the function in my body tag:
<script type="text/javascript">
  function format_number_euro(number) {
    let formatter = new Intl.NumberFormat('nl-NL', {style: 'currency', currency: 'EUR'})
    return formatter.format(number)
  }
</script>

Then later on, I call it to format numbers:

<div class="card-body">
  <span class="font-weight-bolder display-4 text-dark-75 py-4 pl-5 pr-5">
    <script> format_number_euro( {{ total }} ) </script>
  </span>
</div>

total variable is coming from my Python code which passes the variable when retrieved from the data (I think this is Jinja?):

@app.route("/summary", methods=["GET", "POST"])
@login_required
def summary(total):
    return render_template("summary.html", total=total)

But this does not return anything. Which mistake am I making here?

Upvotes: 0

Views: 44

Answers (1)

Phil
Phil

Reputation: 164879

If you want to insert a value into your HTML document, you need to use DOM methods like Element.append().

For example

<script>
function format_number_euro(number) {
  let formatter = new Intl.NumberFormat('nl-NL', {
    style: 'currency',
    currency: 'EUR'
  })
  return formatter.format(number)
}
</script>

<div class="card-body">
  <span class="font-weight-bolder display-4 text-dark-75 py-4 pl-5 pr-5">
    <script>
      // Append the text value to this script tag's parent element
      document.currentScript.parentElement.append(format_number_euro(25412))
    </script>
  </span>
</div>

See also Document.currentScript and Node.parentElement

Upvotes: 1

Related Questions