1

I'm trying to add a duplicate function to clone and append a div. Here's the JS:

function NL(){
  var original = document.getElementsByClassName('form-block')[0];
  var clone=original.cloneNode(true);
  document.getElementsByTagName('form')[0].appendChild(clone);
}

document.getElementsByClassName('new-line')[0].addEventListener('click',NL);

and the HTML:

<form class='myform'>
  <div class='form-block'>
    <span class='line'>1</span>
    <button class='new-line'>New Line</button>
    <button class='new-nested'>New Nested Line</button>
    <input class='input' type='text' placeholder='Enter Value...'>
    <button class='new-input'>Add input</button>
  </div>
</form>

CodePen Link

The idea is when you click the "New Line" button, a new 'form-block' is cloned and appended under the first one. But if you click on the "New Line" button now, the new block shows up briefly and then disappears. I can't figure out why.

I can't modify anything in the HTML, and I can only use vanilla JS.

Thanks!

Bismo Funyuns
  • 73
  • 1
  • 7
  • 1
    I think (am not sure), every time you click the button, the `form` gets submitted and hence the page reloads. Yep, I was right. http://stackoverflow.com/questions/4667979/whats-the-standard-behavior-when-button-tag-click-will-it-submit-the-form – Gaurang Tandon Mar 25 '17 at 03:04

2 Answers2

3

button default type is submit. When there is no type specified it will act as a submit button & in your case it is trying to make a post call. You can open the developers console and check the network tab. In order to prevent that use preventDefault()

function NL(event){
event.preventDefault()  // Here is the change
  var original = document.getElementsByClassName('form-block')[0];
  var clone=original.cloneNode(true);
  document.getElementsByTagName('form')[0].appendChild(clone);
}

document.getElementsByClassName('new-line')[0].addEventListener('click',NL);

DEMO

brk
  • 48,835
  • 10
  • 56
  • 78
2

Just use type="button"

<button type="button" class='new-line'>New Line</button>
<button type="button" class='new-nested'>New Nested Line</button>
Redhya
  • 663
  • 7
  • 21