簡體   English   中英

如何計算兩個文本框並在另一個文本框中顯示答案?

[英]How do I calculate two text boxes and display the answer in another?

我正在嘗試添加兩個文本框並在第三個中顯示結果,每當我嘗試添加第三個框時,它都會使其無效。 有什么建議? 這是我的代碼!


    <br>
    <br>
    <p4>Calculate Two Fields</p4>
    <p4 id="answer"></p4>
    <br>
    <br>

    Number 1<input type="text" id="num1" <br>
    <br>
    Number 2<input type="text" id="num2" <br>
    <br>
    <button onclick="calculate()">Calculate</button>

    <script>
        function calculate() {
            var field1 = document.getElementById(num1).value;
            var field2 = document.getElementById(num2).value;

            var result = parseFloat(field1) + parseFloat(field2)

            if (!isNaN(result))

            {
                document.getElementById("answer").innerHTML = "The answer is " + result;

            }
    </script>

嘗試.....

 $("#second").keyup(function() { var total = 0; $('.smtab_tot').each(function(_i, e) { var val = parseFloat(e.value); if (!isNaN(val)) total += val; }); $('#total').val(total); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> input 1 : <input type="number" class="smtab_tot" id="first"> <br> input 2 : <input type="number" class="smtab_tot" id="second"> <br> total : <input type="text" id="total">

我看不出任何錯誤,除了; }

最好使用onchange或其他事件事件來刪除點擊以獲得更好的 ui/ux。

但是你可以用angularjs更好地做到這一點。你可以為每個輸入使用ng-model並在第三個輸入中寫入{{model1+model2}}

你也可以用vue.js不同的是你應該使用vmodel而不是ng-model

getElementById('num1')此處的id應在引號中,否則將被視為變量。

你也忘記了最后的}

 function calculate() { var field1 = document.getElementById('num1').value; var field2 = document.getElementById('num2').value; var result = parseFloat(field1) + parseFloat(field2); if (!isNaN(result)) { document.getElementById("answer").textContent= "The answer is " + result; } }
 <br> <br> <p4>Calculate Two Fields</p4> <p4 id="answer"></p4> <br> <br> Number 1<input type="text" id="num1" <br> <br> Number 2<input type="text" id="num2" <br> <br> <button onclick="calculate()">Calculate</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM