Vishal Vishal - 4 months ago 17
jQuery Question

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.

    Answer

    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>