Frank W. Frank W. - 5 months ago 9
jQuery Question

unable to find the item that got user input with dynamically created items

Hi there I am encountering the following problem I have 3 div's dynamically loaded by ajax like so:

<div class="item" id="item1"> // Dynamically loaded
<input>
<input>
</div>
<div class="item" id="item2"> // Dynamically loaded
<input>
<input>
</div>
<div class="item" id="item3"> // Dynamically loaded
<input>
<input>
</div>

$(document).on('change', '.item', function() {


});


What I want to achieve is when I make a change on the input of one of the three div's, I wanna know where the input was provided. Because the elements are dynamically loaded I can't use a direct selector but I have to use
$(document).on
and because I dont make use of the direct selector I can't make use of
(this)
. How do I find out in what item changes have been made?

Thanks in advance!

Answer

The first argument of the handler - for instance e - would receive the event if it is declared. Then the e argument is having target property which gives you the HTML element on which the event originated. So this would give you a reference to the changed input:

$(document).on('change', '.item', function(e) {
    var targetInput = e.target;
    var parent = $(targetInput).closest("div.item");
    // Do something ...
});
Comments