javascript how to add element dynamically to form tag using button

Viewed 243

i have a html view with form tag, i need to add dynamically text to the form using a button click, the full code is below work well when i remove the <form> tag, but when i keep the form tag is doenst work, seems like the page is refreshing and text is disappearing

<html>
    <body>
  <form  >
<button onclick="create()">Create Heading</button>

</form>

    <script>
  function create() {
    var h1 = document.createElement('h1');
    h1.textContent = "New Heading!!!";
    h1.setAttribute('class', 'note');
    document.body.appendChild(h1);
  }
</script>
2 Answers

Use event.preventDefault() to prevent the default action:

function create(event) {
  event.preventDefault(); //add this
  var h1 = document.createElement('h1');
  h1.textContent = "New Heading!!!";
  h1.setAttribute('class', 'note');
  document.body.appendChild(h1);
}
<form>
  <button onclick="create(event)">Create Heading</button>
</form>

You need to prevent default submit behavior with preventDefault()

<html>
    <body>
  <form  >
<button onclick="create(e)">Create Heading</button>

</form>

    <script>
  function create(e) {
e.preventDefault();
    var h1 = document.createElement('h1');
    h1.textContent = "New Heading!!!";
    h1.setAttribute('class', 'note');
    document.body.appendChild(h1);
  }
</script>
Related