0

When I click on the "click me" button after entering the value as 22 I don't see any changes on the web page. How can I fix this?

function fun() {
  n = document.getElementById("number").value;
  headingTag = document.getElementById("h2");
  headingTag.innerText = n;
}
<form>
  <input type="text" id="number">
  <button onclick="fun()">Click Me!</button>
</form>
<h2 id="h2"></h2>
Martijn Vissers
  • 712
  • 5
  • 29
taurus05
  • 2,491
  • 15
  • 28

2 Answers2

0

Use preventDefault() to stop the form submit behaviour by the button. Refer

function fun(e) {
  e.preventDefault();
  n = document.getElementById("number").value;
  headingTag = document.getElementById("h2");
  headingTag.innerText = n;
}
<body>
  <form>
    <input type="text" id="number">
    <button onclick="fun(event)">Click Me!</button>
  </form>
  <h2 id="h2"></h2>
</body>
ellipsis
  • 12,049
  • 2
  • 17
  • 33
-1

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>
Mamun
  • 66,969
  • 9
  • 47
  • 59