0

I am trying to make a website, in which one makes a questions and there will be options for that questions.

I have a add option button, when user clicks the add option button, new option is added by this function.

function addOption(elem) {
            elem = $(elem);
            let ul = $(elem.parent().children()[1]);

            let addedElem = $(
                `<li class='ques-li'><input type='text' name='ques-option' class='ques-option' value='Option'><p class='remove-op'>X</p></li>`
            );
            addedElem.appendTo(ul);

        }

let addOp = $('.ques-add');
$('.ques-add').click(function () {
            addOption($(this));
});

This works well with one question, but when a user adds another question.

It is by this function.

let addQuestion = $('form button');
        addQuestion.click(function () {
            let quesBox = $('div.questions-box');
            quesBox.html(quesBox.html() + `<div class='ques'>
                <input type="text" name="ques-name" class="ques-name">
                <ol class='ques-ul'>
                    <li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
                        <p class='remove-op'>X</p>
                    </li>
                    <li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
                        <p class='remove-op'>X</p>
                    </li>
                </ol>
                <p class='ques-add'>Add Another</p>
            </div>`)
        });

When i click the add Question button, it also works

but when i click the add option button on a newly created question, it does not create a new option.

I noticed when i create a new question, it does not get the new option button.

So, i updated my code as follows :-

let addOp = $('.ques-add');
        $(document).bind('DOMNodeInserted', function(){
            addOp = $('.ques-add');
        });
        addOp.click(function () {
            addOption($(this));
        });

It also does not work.

I have no idea why this code is not working.

Thanks in advance.

programmer pro
  • 169
  • 1
  • 2
  • 12
  • 2
    Because the newly created element doesn't fire on click(). So you should use somthing like this -> $(document).on('click', '.ques-add', fuction() {...}); – Beller May 31 '20 at 08:07
  • I strongly advise against using any 3rd party library before your native Javascript skills are fluent. – connexo May 31 '20 at 10:34

1 Answers1

3

Try using delegation approach that uses .on(). This will assure that the event will be attached to all the elements that are added to the document at a later time:

$('body').on('click', '.ques-add', function () {
  addOption($(this));
});
Mamun
  • 66,969
  • 9
  • 47
  • 59