0

I have been trying to add two values from two input fields together with a simple js function. Not working, please help.

<input class = "field1" type="text">
<input class = "field2" type="text">
<p class = "field3"></p>
<button onclick = "calculate()">Calculate</button>

<script>
function calculate(){
let ipt1 = document.getElementsByClassName("field1").value;
let ipt2 = document.getElementsByClassName("field2").value;
let results = document.getElementsByClassName("field3");
let total = Number(ipt1 + ipt2);
return results.innerHTML = total;
}
</script>
  • Also note that if you want to get the sum of the two numbers, you need to convert them to a number _before_ you use the `+` operator. – Ivar Oct 26 '21 at 08:16
  • `getElementsByClassName` returns a list (or array) of elements (getElementS with a S). An array has no "value" property. You can't do `["a","b","c"].value`, it doesn't make sense. You have to iterate over this array and take its elements one by one. Each element does have a `.value` indeed. – Jeremy Thille Oct 26 '21 at 08:20

1 Answers1

0
<input class = "field1" type="text">
<input class = "field2" type="text">
<p class = "field3"></p>
<button onclick = "calculate()">Calculate</button>

<script>
function calculate(){
let ipt1 = document.getElementsByClassName("field1")[0].value
let ipt2 = document.getElementsByClassName("field2")[0].value
let results = document.getElementsByClassName("field3")[0]
let total = Number(ipt1) + Number(ipt2)
return results.innerHTML = total;
}
</script>