0

Im having a problem attaching an event to a dynamically generated button. However after some research most of the solutions claim this error is usually generated from a form control. However in my case the error "invalid form control with name='answer'" is being generated and triggered when a button i have dynamically generated is pressed :

   $("#BoxInner").append($("<button id='dynamicButton' class='btn btn-success' onclick='clickEvent()'>"+ "Button"+"</button>"));

I have appended a button to an existing div and call an onclick function that removed this element when it is clicked like this :

function clickEvent()
{
$(this).remove();
}

After running this in chrome this method works only on the first button added. After the first button is removed as expected it begins to generate the error "clickEvent" and adding a number count on each click and after reading many posts here about the error being attributed to a form i remain unsure how to solve the issue as the button is completely unrelated to the form on my HTML document and subsequently setting the form to not require validation does not solve the issue with the "novalidate" property. But note, if i remove the attached onclick event the error is not triggered.

Any help would be appreciated :)

Community
  • 1
  • 1
D3181
  • 2,037
  • 5
  • 19
  • 44

2 Answers2

2

$("#BoxInner").append($("<button id='dynamicButton' class='btn btn-success' onclick='clickEvent(this)'>"+ "Button"+"</button>")); // pass this to clickEvent function

function clickEvent(obj)
{
   $(obj).remove();  // remove button like this
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="BoxInner"></div>
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
1

This is because the event listener is created on page load.

You should do something like this

$(wrapper_that_always_exists).on('click', the_freshly_added_element, function() {
    ...
});

So in your example it would be something like

$('#BoxInner').on('click', '#dynamicButton', function() {
    ...
});

When you do this, the BoxInner element will always listen for all clicks on any element inside, initially created or not, that has the id dynamicButton

Jonathan Nielsen
  • 1,442
  • 1
  • 17
  • 31