Vishal
Vishal

Reputation: 6368

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.

    Upvotes: 0

    Views: 103

    Answers (2)

    aebabis
    aebabis

    Reputation: 3705

    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>

    Upvotes: 1

    Whothehellisthat
    Whothehellisthat

    Reputation: 2152

    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.

    Upvotes: 0

    Related Questions