1

I have created a simple js code:

var testContainer = document.getElementById("test");
var butt = document.getElementById("test-button");

butt.addEventListener("click", function(){
    var paragraph = document.createElement("p");
    paragraph.innerText = "test";
    testContainer.appendChild(paragraph);
});

With HTML code:

<form>
  <div id="test"></div>
  <button id="test-button"> test </button>
</form>

And here is the JSFiddle.

My question is why when <button> is inside <form> then my event listener is blocked and it cannot add a new element to <div id="test">? I don't understand why it's not valid.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
A. Dziedziczak
  • 193
  • 3
  • 12

3 Answers3

4

Working fiddle.

Since the button is inside a form it will be considered as a submit button, so when you click in the button the form will be submited then the event will not fire, To avoid that you could add type='button' to the button like :

<button id="test-button" type="button">test</button>

Or use preventDefault() like :

butt.addEventListener("click", function(e){
    e.preventDefault();

    var paragraph = document.createElement("p");

    paragraph.innerText = "test";
    testContainer.appendChild(paragraph);
});

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
3

It appears your button is triggering the form to submit, thus refreshing the page. Try adding e.preventDefault() to your click handler to prevent the form from submitting..

var testContainer = document.getElementById("test");
var butt = document.getElementById("test-button");
butt.addEventListener("click", function(e) {
  e.preventDefault();
  var paragraph = document.createElement("p");
  paragraph.innerText = "test";
  testContainer.appendChild(paragraph);
});
<form>
  <div id="test">

  </div>
  <button id="test-button">
test
</button>
</form>
Woodrow
  • 2,740
  • 1
  • 14
  • 18
1

Change the type of your button to

type="button"
orabis
  • 2,749
  • 2
  • 13
  • 29