I am trying to add the two text boxes and show the result in a third, whenever I try to add the third box, it makes it invalid. Any suggestions? Here is my code!
<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>
Try.....
$("#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">
I cant see any mistake except ;
or }
.
Its better to use onchange
or other events events to remove clicking to get better ui/ux.
But you can do it with angularjs
better.you can use ng-model
for each input and in third input write {{model1+model2}}
.
You can do it with vue.js
too .the different is that you should use vmodel
instead of ng-model
.
getElementById('num1')
here id
should be in quote, otherwise it will be treated as variable.
Also you forgot the }
at the end
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.