Don't use an ID twice in an document and the values you get from the input fields are strings and you do an string addition, so you have to parse it to integer before. The HTML5 input type number
onlys displays in some new browsers a field which is invalid for other characters than numbers, but you get a string when you read the value of it with javascript.
You can parse your strings with parseInt
. If you want to support float, you can use parseFloat
.
num1:<input id="num1" type="number">
num2:<input id="num2" type="number">
<button type="button" onclick="myFunction()">compute</button>
answer:<input id="demoInput" type="text"> and answer: <p id="demoHtml"></p>
<script>
function myFunction() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var ans = parseInt(x) + parseInt(y)
document.getElementById("demoInput").value = ans;
document.getElementById("demoHtml").innerHTML = ans;
}
</script>
By the way:
If you want to name two or more elements with the same ID, use the class attribute. And you get with document.getElementsByClassName("demo")
an array of your elements.