Appending sections in jQuery is adding too many html blocks

Courtney Whiting
Courtney Whiting used Ask the Experts™
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

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software Engineer
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:
Courtney WhitingConversion Lead / Information Architect


Perfect solution. Thanks very much.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial