A
A
Abra Kadabra2015-10-14 13:15:29
JavaScript
Abra Kadabra, 2015-10-14 13:15:29

Why is the element added to the page not responding to a click?

Good afternoon.
There was a need to add elements to the form.
I do it like this . I roughly sketched how everything should look like.
Items are added. But the click only works on the one that was originally on the page.
You can verify this by clicking on the very first drop-down list (an alert will give its number in the form).
The click looks like this:

$(".select").click(function(e){
    var elementId =  $(this).attr("data-form");
    alert(elementId);
    form['selectedSubject'+elementId] = "Select subject";
    $("#subject-select"+elementId).toggleClass("show");
  });


And adding an element like this:
$("#add-subject").click(function(){
  
//перечисление элементов, изменение номеров их ID    
var blockToAdd = '<label for="subject-select'+subjectNumber+'">Subject <span>*</span></label>
<ul class="select" id="subject-select'+subjectNumber+'" data-form="'+subjectNumber+'"><li class="option default active">Select subject</li><li class="option">Math</li<li class="option">Programming</li>
<li class="option">Programming math</li><li class="option">Math in Programming</li></ul>
<label for="hours">Hours <span>*</span></label><div class="hours" id="hours'+subjectNumber+'">
<div class="hours-minus" id="hours-minus'+subjectNumber+'"></div><div class="hours-amount" id="hours-amount'+subjectNumber+'"></div><div class="hours-plus" id="hours-plus'+subjectNumber+'">
</div></div><label for="message">Remarks</label><textarea name="message" id="message'+subjectNumber+'" placeholder="Type your message"></textarea>';
  
          $("#add-subject").before(blockToAdd);	
        //$("#add-subject").after(blockToAdd);
        //$("#add-subject").prepend(blockToAdd);
        //$("#add-subject").append(blockToAdd);
  subjectNumber++;
});

With these 4 options I tried to add elements.
What could be the problem ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Novikov, 2015-10-14
@Jmaster

because event handlers are added to dynamic elements via on:

$(document).on("click","#element",function() {
...
});

D
Denis Ineshin, 2015-10-14
@IonDen

You need event delegation . The essence of the method is that we hang the event handler on the root element, it is possible in general on document. Further, thanks to the ascent, all events rise from below to this node, including the events of elements added later. All that's left is to check the source in the event object against our target and call the callback. With jQuery, this is done elementarily, as shown by Dmitry Novikov

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question