简体   繁体   English

Javascript:如何使用 javascript 在循环中计算多个输入值?

[英]Javascript: how to get calculate multiple input values in loop using javascript?

I am trying to calculate the value of some input field in my Django template using javascript ( onkeyup=() , the form is in a loop eg {% for p in prediction %} {% endfor %}.我正在尝试使用 javascript( onkeyup=() ,表单在循环中计算我的 Django 模板中某些输入字段的值,例如 {% for p in prediction %} {% endfor %}。

I have this simple line to grab the input values (NOTE: They are in a loop)我有这条简单的线来获取输入值(注意:它们在一个循环中)

   let stake_amount_input = document.querySelector("#amount").value
   let shares_amount_input = document.querySelector("#shares").value

Based on the fact that I have all these functions in a Django loop, am I not supposed to get all the input field values when I calculate the other objects in the loop?基于我在 Django 循环中拥有所有这些函数的事实,我是否应该在计算循环中的其他对象时获取所有输入字段值?

Based on the fact that I have all these functions in a Django loop, am I not supposed to get all the odds when I console.log(odds)基于我在 Django 循环中拥有所有这些功能的事实,我不应该在我 console.log(odds) 时获得所有赔率

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

    <script>
      function CalculateNewBalance(){
          let stake_amount_input = document.querySelector(".amount").value
          let shares_amount_input = document.querySelector(".shares").value
          let potential_win = document.querySelector(".potential-win")

          let potential_win_value = parseFloat(stake_amount_input) * parseInt(shares_amount_input)
          potential_win.innerHTML = "$" + potential_win_value
          
          // if the potential_win innerHTML shows Nan, then i want to change the innerHTML to $0.00, but this is not working too
         if (potential_win === isNan) {
             potential_win.innerHTML = "$0.00"
         }

                                                        
    </script>
    </form>
{% endfor %}

在此处输入图像描述 在此处输入图像描述

EDIT: My template编辑:我的模板

<div class="mid-area">
    <div class="single-area">
        <div class="item-title d-flex align-items-center justify-content-between">
            <span>Choose Stake Amount</span>
        </div>
        <div class="d-flex in-dec-val">
            <input type="number" required value="{{ p.amount }}" name="amount" placeholder="amount" class="shares" />

            <div class="btn-area">
                <button class="plus" type="button">
                    <img src="{% static 'assets/images/icon/up-arrow.png' %}" alt="icon" />
                </button>
                <button class="minus" type="button">
                    <img src="{% static 'assets/images/icon/down-arrow.png' %}" alt="icon" />
                </button>
            </div>
        </div>

        <p id="error-div" class="mt-2"></p>
    </div>
    <div class="single-area quick-amounts"></div>
    <div class="single-area quick-amounts">
        <div class="item-title d-flex align-items-center">
            <p>Choose <b>Shares</b> Amount</p>
        </div>
        <div class="d-flex in-dec-val">
            <input type="number" required value="1" name="shares" placeholder="shares" class="shares" />

            <div class="btn-area">
                <button class="pldus" type="button">
                    <img src="{% static 'assets/images/icon/up-arrow.png' %}" alt="icon" />
                </button>
                <button class="mindus" type="button">
                    <img src="{% static 'assets/images/icon/down-arrow.png' %}" alt="icon" />
                </button>
            </div>
        </div>
    </div>

    <div class="single-area smart-value">
        <div class="item-title d-flex align-items-center">
            <p class="mdr text-capitalize">Potential win</p>
        </div>
        <div class="contact-val d-flex align-items-center"><span style="font-size: 24px;" class="potential-win">$0.00</span><br /></div>
    </div>
</div>

You have to add unique name every time you loop.每次循环时都必须添加唯一名称。 Variable names and Id's should be unique.变量名称和 ID 应该是唯一的。 For this you have to add counter or unique values.为此,您必须添加计数器或唯一值。 Check this answer for how to add counter.检查此答案以了解如何添加计数器。

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

    <script>
      function CalculateNewBalance(){
          let stake_amount_input{{ forloop.counter }} = document.querySelector(".amount{{ forloop.counter }}").value
          let shares_amount_input{{ forloop.counter }} = document.querySelector(".shares{{ forloop.counter }}").value
          let potential_win{{ forloop.counter }} = document.querySelector(".potential-win{{ forloop.counter }}")

          let potential_win_value{{ forloop.counter }} = parseFloat(stake_amount_input{{ forloop.counter }}) * parseInt(shares_amount_input{{ forloop.counter }})
          potential_win{{ forloop.counter }}.innerHTML = "$" + potential_win_value{{ forloop.counter }}
          
          // if the potential_win innerHTML shows Nan, then i want to change the innerHTML to $0.00, but this is not working too
         if (potential_win{{ forloop.counter }} === isNan) {
             potential_win{{ forloop.counter }}.innerHTML = "$0.00"
         }

                                                        
    </script>
    </form>
{% endfor %}

{{ forloop.counter }} returns a list of numbers from 1 to number, until for loop runs. {{ forloop.counter }}返回一个从 1 到 number 的数字列表,直到 for 循环运行。

The This would make every id unique and every variable unique.这将使每个 id 和每个变量都唯一。 For example, when the loop runs例如,当循环运行时

for first time:第一次:

let potential_win1 = document.querySelector(".potential-win1").value

for second time:第二次:

let potential_win2 = document.querySelector(".potential-win2").value

and so on.等等。

Instead of putting whole form & script inside loop just add input fields inside loop and then either set event on each element inside loop or add event listener programmatically.不是将整个表单和脚本放在循环内,而是在循环内添加输入字段,然后在循环内的每个元素上设置事件或以编程方式添加事件侦听器。 I'll show programmatic approch.我将展示编程方法。

<form action="#" method="POST">
{% for p in prediction.prediction_data.all %}
     <input type="number" value="" name="amount" class="shares" onkeyup="CalculateNewBalance()">
     <input type="number" value="" name="shares" class="shares" onkeyup="CalculateNewBalance()">
{% endfor %}
</form>
 let inputs = document.querySelectorAll('input');
function CalculateNewBalance(e) {
    let target = e.target
    let potential_win_value;
    let potential_win;

    if (target.nextElementSibling.classList.contains('potential-win')) {
        potential_win = target.nextElementSibling
    } else {
        potential_win = target.nextElementSibling.nextElementSibling
    }

    if (target.nextElementSibling.classList.contains('shares')) {
        potential_win_value = parseFloat(target.nextElementSibling.value) * parseInt(target.value)
    } else {
        potential_win_value = parseFloat(target.previousElementSibling.value) * parseInt(target.value)
    }

    potential_win.innerHTML = "$" + potential_win_value

    if (potential_win.innerHTML == '$NaN') potential_win.innerHTML = '$0.00'
}

['input', 'change'].forEach(evt => {
    inputs.forEach(input => input.addEventListener(evt, CalculateNewBalance, false))
});

Here is working example这是工作示例

 let inputs = document.querySelectorAll('input'); function CalculateNewBalance(e) { let target = e.target let potential_win_value; let potential_win; if (target.nextElementSibling.classList.contains('potential-win')) { potential_win = target.nextElementSibling } else { potential_win = target.nextElementSibling.nextElementSibling } if (target.nextElementSibling.classList.contains('shares')) { potential_win_value = parseFloat(target.nextElementSibling.value) * parseInt(target.value) } else { potential_win_value = parseFloat(target.previousElementSibling.value) * parseInt(target.value) } potential_win.innerHTML = "$" + potential_win_value if (potential_win.innerHTML == '$NaN') potential_win.innerHTML = '$0.00' } ['input','change'].forEach( evt => { inputs.forEach(input => input.addEventListener(evt, CalculateNewBalance, false)) } );
 <form action="#" method="POST"> <input type="number" value="" name="amount" placeholder="amount" class="shares"> <input type="number" value="" name="shares" placeholder="shares" class="shares"> <span class="potential-win">$0.00</span><br /> <input type="number" value="" name="amount" placeholder="amount" class="shares"> <input type="number" value="" name="shares" placeholder="shares" class="shares"> <span class="potential-win">$0.00</span><br /> <input type="number" value="" name="amount" placeholder="amount" class="shares"> <input type="number" value="" name="shares" placeholder="shares" class="shares"> <span class="potential-win">$0.00</span><br /> </form>

Note:笔记:

  1. If you're creating application which includes real transactions & calculations of amount you should not rely on client side calculation handle it on server side.如果您正在创建包含实际交易和金额计算的应用程序,则不应依赖客户端计算在服务器端处理它。
  2. Don't use ID inside loop it shold be unique不要在循环中使用 ID 它应该是唯一的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM