Search code examples
jquerydrop-down-menujquery-selectorsdropdown

Get value of clicked dropdown item


I have this dropdown menu

<ul class="dropdown-menu"></ul>

whose <li> items are populated by jquery from a database table

success:function(data){
$(".dropdown-menu").empty();
$.each(data, function(key, value){
     $(".dropdown-menu").append("<li>" + key +   "</li>"); 
});

I want to get the text of the <li> item clicked on by the user. I have tried

$(document).ready(function () {  
      $(".dropdown-menu").click(function(){
            var sel=$(".dropdown-menu .selected").text();
            alert(sel);
       });
});     

I have tried the solutions in

and several others to no avail.

The alert box is coming up blank.

How can I get the value of the clicked item? I cannot use the select option. Thank you


Solution

  • So, I changed my code to

    <div class="dropdown">
        <div>
        <input class="form-control" name="query" placeholder="Search End User" data-toggle="dropdown">          
        <div class="dropdown-menu" >
        </div></div></div>
    

    Then I populated the dropdown-items from an sql table as follows:

    success:function(data){
        $(".dropdown-menu").empty();
        $.each(data, function(key, value){
        $(".dropdown-menu").append("<button class='dropdown-item' type='button'>" + key + "</button>");});
    

    then I processed the selection of the dropdown-item from the dropdown-menu as follows:

    $(document).ready(function () {  
        $(".dropdown-menu").hover(function(){ 
            $(".dropdown-item").on("click",(function(){
                alert("click detected");
                var sel=$(this).text();
                alert(sel);
          }));
          });
     }); 
    

    Here I split the click event into two. First event is the mouse hovering over the dropdown-menu then the user clicks on the dropdown-item. Now when I click on the dropdown-item the alert box returns the clicked value. This has solved my problem.