Reputation: 6368
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 :
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
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
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