1

This is the dropdwon

<div class="col-md-6">
             <div class="dropdown">
                <input  type="text" data-toggle="dropdown" id="search-input" class="form-control">
                <ul class="dropdown-menu" id="employee-list">
                  <!--filled by ajax -->
                </ul>
              </div>
        </div>

and I get the list with aand itry to get the click event but nothing its done

$(document).ready( function(){
    $('#search-input').keyup(function(e){
        if($(this).val().length >= 3 /*&& e.which != 8*/ ){
            get_users($(this).val());
        }
    });

    $(".dropdown-menu li a").click(function(){
        alert('aaaa');
    });
});

Ineed to click a list element and set the text of the input with the text of the clicked element but I can't handle the click event

function get_users($text){
    $.ajax({
      url: "asociate_ci.php",
      method: 'get',
      data: {
        'text': $text ,
        'option':'get_users' 
      }
    })
      .done(function( response ) {
        var employees = JSON.parse(response);
        //console.dir(employees);
        $('#employee-list').empty();
        $.each(employees, function(){
            //console.log(this.last_name);
            $('#employee-list').append("<li ><a class='employee-li'>"+this.last_name+"</a></li>");
        });
        $('#search-input').focus();
      });
}
Af_doubts
  • 45
  • 7

2 Answers2

2

You need to use on using a single handler a for all elements that match your selector .dropdown-menu. This will be able to bind to dynamically created elements.

// $(".dropdown-menu") = watch for any changes to the dom inside this element
// 'click' = event type
// a = add click event to these elements
$('.dropdown-menu').on('click', 'a', function(){
    alert('aaaa');
});
WizardCoder
  • 3,353
  • 9
  • 20
0

jquery handlers on present elements they work fine, but the new elements are not binded to those handlers so thats why we need to use the .on() method.

Change your click event like below:

$('.dropdown-menu').on('click', 'a', function(){
   alert('aaaa');
});
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33
  • 1
    It is best practice to use a specific selector rather than the entire `document`, because of performance issues. This guy explains it well: https://stackoverflow.com/a/12824698/8085668. I imagine you are aware of this, I just thought I would mention it for anyone else. – WizardCoder Jun 08 '17 at 10:18