0

I am trying to active function when clicking on button which is created with createElement.

On html code:

<fieldset class="form-fieldset">
   <button type="button" class="btn-ref">Hello</button>
</fieldset>

On javascript:

$('.btn-ref').click(function(){
   var newButton = document.createElement('button');
   newButton.className="btn-ref";
   $('.form-fieldset').append(newButton);
});

On original code, when clicking on button does create new button. But after clicking on created button, it does not create new button.

Can someone tell me what is wrong?

Junie
  • 59
  • 2
  • 10

1 Answers1

0

You can add button name by getting its value textContent :- returns the text content of the specified node value.

It will find on body where this className used will createElement dynamically and applies value to it.

$("body").on("click", ".btn-ref", function(event) {
    var newButton = document.createElement('button');
    newButton.className = "btn-ref";
    newButton.textContent = $(this).text();
    $('.form-fieldset').append(newButton);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset class="form-fieldset">
    <button type="button" class="btn-ref">Hello</button>
</fieldset>
Parth Raval
  • 4,097
  • 3
  • 23
  • 36