2

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 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.