How to add event liteners in Django?

I have the following code in html with a js script, but i want to add it to my django forms but i don't know how or where to start. What it does is that it automatically multiplies two numbers as the user types and shows the predict in a different part of the table.

    {% extends "blog/base.html" %} {% block content %}
<h1>About Page</h1>

<div class="container">
  <h2>Basic Table</h2>
  <form>
    <table class="table">
      <thead>
        <tr>
          <th>Value</th>
          <th>Amount</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>10</td>
          <td>
            <div class="form-group">
              <label for="usr"></label>
              <input type="text" class="form-control" id="num1" />
            </div>
          </td>
          <td>
            <div id="total"></div>
          </td>
        </tr>
        <tr>
          <td>20</td>
          <td>
            <div class="form-group">
              <label for="tt"></label>
              <input type="text" class="form-control" id="num2" />
            </div>
          </td>
          <td>
            <div id="total 2"></div>
          </td>
        </tr>
        <tr>
          <td>30</td>
          <td><div class="form-group">
              <label for="ttt"></label>
              <input type="text" class="form-control" id="num3" />
            </div></td>
          <td><div id="total 3"></div></td>
        </tr>
      </tbody>
    </table>
  </form>
</div>
<script>
  function multiply(a, b, outputId) {
    var total = a * b;
    document.getElementById(outputId).innerHTML = total;
  }

  const num1 = document.getElementById('num1');
  const num2 = document.getElementById('num2');
  const num3 = document.getElementById('num3');

  num1.addEventListener('input', (event) => {
    console.log(event);
    multiply(10, Number(event.target.value), 'total');
  });

  num2.addEventListener('input', (event) => {
    multiply(20, Number(event.target.value), 'total 2');
  });

  num3.addEventListener('input', (event) => {
    multiply(30, Number(event.target.value), 'total 3');
  });
</script>

{% endblock content %}

I know that this must be done in mt views.py function but i dont know how or where to start.

Вернуться на верх