1

I am trying to get the value of some input field in my django template, the form is in a loop e.g {% for p in prediction %} {% endfor %}.

I have this simple line to grab the id from the input field let odds = document.getElementById("odds").value

Based on the fact that i have all these function in a django loop, am i not supposed to get all the odds when i console.log(odds)

{% for p in prediction.prediction_data.all %}
  <form action="#" method="POST">
     <input type="text" value="{{ p.odds }}" id="odds">
     <input type="number" value="" name="amount" id="amount" onkeyup="CalculateNewBalance()">

    <script>
      function CalculateNewBalance(){
          let odds = document.getElementById("odds").value
          let stake_amount_input = document.getElementById("amount")
                                                 
          console.log(odds);
    </script>
    </form>
{% endfor %}
[![enter image description here][1]][1]

enter image description here

1 Answers1

1

Instead of using id use class or attribute becouse id is used to identify unique element in DOM. Also you don't have to put your script inside loop and instead of adding form inside loop put input fields.

Your final code will look like this

<form action="#" method="POST">
  {% for p in prediction.prediction_data.all %}
     <input type="text" value="{{ p.odds }}" class="odds">
     <input type="number" value="" name="amount" class="amount" onkeyup="CalculateNewBalance(event)">
  {% endfor %}
</form>

<script>
  function CalculateNewBalance(e){
      let t = e.target;
      let odds = t.previousElementSibling.value
      let stake_amount_input = t
      console.log(odds);
  }
</script>

Running code example

function CalculateNewBalance(e){
    let t = e.target;
    let odds = t.previousElementSibling.value
    let stake_amount_input = t
    console.log(odds);
}
<form action="#" method="POST">
    <input type="text" value="1.0" class="odds">
    <input type="number" value="" name="amount" class="amount" onkeyup="CalculateNewBalance(event)">

    <input type="text" value="2.0" class="odds">
    <input type="number" value="" name="amount" class="amount" onkeyup="CalculateNewBalance(event)">
    <input type="text" value="3.0" class="odds">
    <input type="number" value="" name="amount" class="amount" onkeyup="CalculateNewBalance(event)">
  </form>
Ankit Tiwari
  • 4,438
  • 4
  • 14
  • 41
  • 1
    You saved ma a**, thanks alot buddy. – Destiny Franks Dec 18 '22 at 18:37
  • Hi again, i have a little issue that i have been encountring since that day you helped me. i want to calculate two input fields and add then to the innerHTML, the first one in the loop gets calculated but the other once in the loop does not. – Destiny Franks Dec 21 '22 at 09:27
  • I made a diffrent question for that, here it is https://stackoverflow.com/questions/74873802/javascript-how-to-get-calculate-multiple-input-values-in-loop-using-javascript – Destiny Franks Dec 21 '22 at 09:27