Appending sections in jQuery is adding too many html blocks

I am attempting to have clickable "Add Section" buttons that when clicked will generate and HTML code block. There is a main block and a sub-block. I have it mostly working but the issue comes when I have several main blocks on the screen and I start adding the sub-blocks. I want to only add one block at a time but every time I add a new main block and then a sub block to the previous main block, a sub block for every new main block is added. How can I add just one each time? Follow my JSFiddle link for clarification.

- "main block" is triggered when "Add Question Block" is clicked
- "sub block" is triggered when "Add answer" is clicked

Courtney WhitingConversion Lead / Information ArchitectAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Robert SchuttSoftware EngineerCommented:
The duplication happens because the click event itself is duplicated: it is added to existing buttons again when a new question block is added. You can either try to remedy that from happening or use event delegation to define the click event once, outside the 'add question' click event.
  $('.js-section-main').on('click', '.js-add-pvo-answer-block', function(event) {
    $('.js-subsection-main', $(this).closest('table')).append(pvoAnswerBlock);

Open in new window

This form of event handling has the advantage that the event is defined on the container and will fire for any child of the correct class even if it has been added to the container at a later time, as is the case here.

I have also saved a new version of the fiddle:

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Courtney WhitingConversion Lead / Information ArchitectAuthor Commented:
Perfect solution. Thanks very much.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.