I have had a lot of problems with this problem. When I console.log(sum);
I get the answer I am looking for, but when I try to output the answer from a button click and an input field it does not work. I changed felt3.innerHTML=addnumber(ttt);
to document.write(addnumber(ttt));
which made it work, but it is sending it to another page, which is something I do not want. How I can make this work:
<form id="form3">
Tall:<input type="number" id="number"><br>
<input type="button" id="button3" value="plusse"><br>
</form>
<div id="felt3"></div>
and:
var number = document.getElementById("number");
var felt3 = document.getElementById("tall3");
var form3 = document.getElementById("form3");
var button3 = document.getElementById("button3");
var sum=0;
function addnumber(x){
var array = [];
array.push(x);
for (var i = 0; i < array.length; i++) {
sum=sum+array[i];
}
return sum;
}
button3.onclick=function(){
var ttt=Number(number.value);
felt3.innerHTML=addnumber(ttt);
}
If I understand your question correctly, then the solution here is to update the argument that you are passing to getElementById("tall3")
, rewriting it to document.getElementById("felt3");
.
Doing this will cause your script to aquire the reference to the div element with id felt3
. When your onclick
event handler is executed, the result of addnumber()
will be assigned to the innerHTML
of the valid felt3
DOM reference as required:
var number = document.getElementById("number"); // Update this line to use "felt3" var felt3 = document.getElementById("felt3"); var form3 = document.getElementById("form3"); var button3 = document.getElementById("button3"); var sum=0; function addnumber(x){ var array = []; array.push(x); for (var i = 0; i < array.length; i++) { sum=sum+array[i]; } return sum; } button3.onclick=function(){ var ttt=Number(number.value); // Seeing that felt3 is now a valid reference to // a DOM node, the innerHTML of div with id felt3 // will update when this click event is executed felt3.innerHTML=addnumber(ttt); }
<form id="form3"> Tall:<input type="number" id="number"><br> <input type="button" id="button3" value="plusse"><br> </form> <div id="felt3"></div>
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.