简体   繁体   中英

Fire click event of li before hiding ul

I have a textbox and then an unordered list like below:

<div>
    <input type="text" />
    <button>Go</button>
</div>
<ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
</ul>

Now in the blur event of textbox:

$('input').on('blur', function() {
    $('ul').hide();
});

The above code works just fine.

I am trying to make something like combobox .

So, my desired behavior is :

  • When Textbox loses focus, suggestions should hide (which is shown above)
  • When Clicked on a suggestion, its click event should fire and then text of that suggestion should be filled in textbox and then all suggestions should hide
  • So, for the second functionality, when I click on any li the click event of li should fire and then ul should be hidden.

     var items = ["Apple", "Banana", "Celery", "Peach", "Plum"]; $('input').on('input', function() { var text = $(this).val(); $('ul').show().empty().append(items.filter(function(item) { return item.match(new RegExp(text, 'i')); }).map(function(text) { return $('<li>').text(text); })); }); $('input').on('blur', function() { $('ul').fadeOut(); }); $('ul').on('click', 'li', function() { $('input[type=text]').val($(this).text()); $('ul').hide(); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div> <input type="text" /> <button>Go</button> </div> <ul> </ul> 

    Simply update the textbox and then hide the ul within the same click event of the li.

    $("li").on("click", function() {
      $("input[type=text]").val(this.text());
      $("ul").hide();
    });
    

    Sorry if the jQuery isn't perfect--I don't use it that often. This should help, anyway.

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM