0
I am building a custom select with autocomplete and for this I am using some <div>
's, one <input>
and jQuery.
I wish it had the same default behavior as a select HTML when you click outside it, it closes.
My HTML, in general, is like this:
<div class="my-select-container">
<input id="my-input" type="text" value="" onkeyup="myAutocomplete(this);">
<div class="my-options-container"></div>
</div>
I’m using the Javascript function myAutocomplete()
to do all the work of auto complete and successfully manipulate the Divs, my only problem is to do the div my-options-container
close when clicking outside the select.
The function myAutocomplete()
is the following:
function autocomplete_region(obj) {
var value = $(obj).val();
// Only executes if there is some text on search input
if (value) {
// Mount request URL
var url = '/options/' + value + '/';
// Send the request to server
$.get(url,
function (response) {
// Continues only if there is a response
var options = (response["options"] == undefined) ? response : response["options"];
if (options.length > 0) {
// Clear old options
$('#my-options-container').html('');
// Populate items
for (var i = 0; i < options.length; i++) {
var href_value = '/?code=' + options[i].code + '/';
var item = '<a id="option_' + i + '" href="' + href_value + '"><div>' + options[i].text + '</div></a>';
$('#my-options-container').html($('#my-options-container').html() + item);
}
// Shows options div
if ($('#my-options-container').is(':hidden'))
$('#my-options-container').show();
} else {
$('#my-options-container').html('<span>Ops! Nenhuma opção disponível.</span>');
// Shows options div
$('#my-options-container').show();
}
});
} else {
// Hides options div
$('#my-options-container').hide();
// Empty options div
$('#my-options-container').html('');
}
}
Guy puts the if script ai in question tb, facilitates to answer you and for similar situation ai
– hugocsl
Want to close select when input is lost
focused
or as native when you click out?– Sergio
@Sergio Quando perder o
focused
would be better.– Thiago Krempser
@hugocsl I found it unnecessary to put the function
myAutocomplete()
on the question why it got relatively large by doing other things like picking up options on an API other than just showing and hiding the<div>
that shows the options.– Thiago Krempser
You are using some component to create the select or are doing in the same hand?
– Sam
@Sam In the same hand.
– Thiago Krempser
Ask the question about the function (or functions) and/or CSS that opens the select. This is the only way to know how to do the reverse (close the select).
– Sam
I’ll put then, one minute.
– Thiago Krempser
Put it there and I’ll adjust my answer more precisely.
– Sam
@hugocsl I put the script.
– Thiago Krempser
@Sam See if you’ve improved the question.
– Thiago Krempser
So. You’re gonna put in
else
of my answer the sameelse
of the autocomplete function. Thiselse
where you have// Hides options div
.– Sam