-3

I have some javascript which generates some html elements, like below:

for (var i = 0; i < suggestions.length; i++) {
                    var suggestion = suggestions[i];

                    var $li = $('<li data-profile-id="'+ suggestion.id + '" data-profile-name="'+suggestion.first_name + ' ' + suggestion.last_name + ' " class="search-name-result" ></li>');
                    $suggestionsUl.append($li);

                    var $img = $('<img src="/img/profile/' + suggestion.picture_url + '" class="search-suggest-img pull-left" />');
                    $li.append($img);

                    var $link = $('<a href="' + suggestion.id + '">' + suggestion.first_name + ' ' + suggestion.last_name + '</a>');
                    $li.append($link);
                }

What I need to be able to do is also assign a function to each dynamically created li element, something like the below code:

$('.search-name-result').on('click', function(e){
            $input.val($('.search-name-result').data('profile-name'));
        });

But im not sure how to assign this to each li when they are created.

Thanks

Zac Powell
  • 2,362
  • 7
  • 42
  • 84

2 Answers2

0

Almost there, but actually delegate it using a parent container like document

$(document).on('click','.search-name-result', function(e){
            $input.val($(this).data('profile-name'));
        });

Also, you can change

$('.search-name-result').data('profile-name'))

to use $(this) like

$(this).data('profile-name'))

since it will be the clicked .search-name-result

AmmarCSE
  • 28,122
  • 5
  • 36
  • 49
0

You should use event delegation for dynamically added elements.

$(document).on('click','.search-name-result', function(e){
        $input.val($('.search-name-result').data('profile-name'));
});
Zee
  • 8,051
  • 5
  • 31
  • 58