This is because, the default type of button is submit. Thus when clicking, the submission of the form is taking place. You can either use Event.preventDefault()
to prevent the event or specify type="button"
in the button:
<body>
<form>
<input type="text" id="number">
<button onclick="fun(event)">Click Me!</button>
</form>
<h2 id="h2"></h2>
<script>
function fun(e){
n = document.getElementById("number").value;
headingTag = document.getElementById("h2");
headingTag.innerText = n;
e.preventDefault();
}
</script>
</body>
By changing the type:
<body>
<form>
<input type="text" id="number">
<button type="button" onclick="fun()">Click Me!</button>
</form>
<h2 id="h2"></h2>
<script>
function fun(){
n = document.getElementById("number").value;
headingTag = document.getElementById("h2");
headingTag.innerText = n;
}
</script>
</body>