How to close autocomplete dropdown on side click - javascript

I user jquery autocomplete to fetch some results and results are displayed but when I click on the side can't close dropdown with returned results.
$(function () {
$("#search").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("TestAutoComplete", "Home")', type: "POST", dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Title
};
}));
}
});
},
minLength: 1,
select: function (event, ui) {
onItemSelect(ui.item);
},
open: function () {
$(this).removeClass('ui-corner-all').addClass('ui-corner-top');
$(this).autocomplete('widget').css('z-index', 999999);
},
close: function () {
$(this).removeClass('ui-corner-top').addClass('ui-corner-all');
}
})
.data('ui-autocomplete')._renderItem = function (ul, item) {
return $('<li>')
.data('autocomplete-item', item)
.append('<p >' + item.label + "</p>")
.appendTo(ul);
};
});

Very stupid error.
$("#search").autocomplete({...
it should be
$(".search").autocomplete({...
and it work.

Your markup isn't totally clear to me from just looking at your js but it would be something like this:
$("html").on("click.autocomplete", function(e){
var $targ = $(e.target || event.srcElement);
if ( !$targ.is( /* searchlist */ ) || !$( /* searchlist */ ).has( $targ ).length ) {
//Close autocomplete
$("html").off(".autocomplete");
}
});

You leave us somehow blinded of your implementation, but assuming a good pattern the solution would be, detect on every click on the document if the element that was clicked (e.target) ) is inside the search else close the searchbox.
$(document).on('click', function(e)
{
var jqTarget = $(e.target);
if ( !jqTarget.closest('#search').length )
{
$("#search").hide();
}
});

var that = $('.autocomplete'); //Define this somewhere in the page to refer later
$('document').on('mousedown', function(e){
if ($(e.target).closest('.autocomplete:not(:visible)').length != 0) {
that.hide();
}
});

Related

jquery autocomplete, how to show all options on focous?

I have below autocomplete code, which works fine When i type one or more letters.
$("body").on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val();
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(".sub-cat").val(ui.item.label);
return false;
},
change: function(event, ui) {
console.log(this.value);
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
I would like to populate the drop down with all of the matching words from the database on just focusing the input box. That means even without typing a single word. When i just focus, the function is called, but nothing within the
function $(this).autocomplete({ is executed. Any idea why autocomplete not working when focus in on the input field?
Use below code it will work as per your requirement.
$("body input.sub-category").each(function{
$(this).on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val();
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(".sub-cat").val(ui.item.label);
return false;
},
change: function(event, ui) {
console.log(this.value);
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
});
If this is not work add status in comment.
I was able to fix by adding one more function. So there is one function executing on keyup and another one on focus.
$("body").on('keyup', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val()?$(this).val():"";
$(this).autocomplete({
minLength: 0,
autoFocus: true,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(this).val(ui.item.label);
return false;
},
change: function(event, ui) {
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
Above one executes on keyup and below one on focus.
$("body").on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val()?$(this).val():"";
$(this).autocomplete({
minLength: 0,
autoFocus: true,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(this).val(ui.item.label);
return false;
},
change: function(event, ui) {
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
$(this).autocomplete("search", "");
});

autocomplete arrow keys not working

im using autocomplete to retrieve data from the database
$('input[name=\'product_name\']').autocomplete({
'source': function(request, response) {
$.ajax({
url: 'index.php?route=checkout/cart/autocomplete&name=' + encodeURIComponent(request), //Controller route
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
label: item['name'],
value: item['product_id']
}
}));
}
});
},
'select': function(item) {
$('input[name=\'product_id\']').val(item['value']);
$('input[name=\'product_name\']').val(item['label']);
},
focus: function(event, ui) {
return false;
}
});
i already put the focus return false but my dropdown arrow keys still not working.
i also tried using event.preventDefault();
There is some problem with your select event handler of jquery-ui-autocomplete. So try this script -
$('input[name=\'product_name\']').autocomplete({
source: function(request, response) {
$.ajax({
url: 'index.php?route=checkout/cart/autocomplete&name=' + encodeURIComponent(request), //Controller route
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
label: item['name'],
value: item['product_id']
}
}));
}
});
},
select: function(event , ui) {
$('input[name=\'product_id\']').val(ui.item.value);
$('input[name=\'product_name\']').val(ui.item.lable);
},
focus: function(event, ui) {
return false;
}
});
jquery-ui-autocomplete event select callback specified:
$( ".selector" ).autocomplete({ select: function( event, ui ) {} });
And hope this will solve your issue.

TypeError: $(...).autocomplete(...).data(...) is undefined

I found error when using jQuery autocomplete.
This notice error in console is
TypeError: $(...).autocomplete(...).data(...) is undefined
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
Code:
Site Name <br/>
<input type="text" name="site_name" id="site_name"><br/>
<input type="hidden" name="site_id" id="site_id">
$().ready(function () {
$("#site_name").autocomplete({
source: function (request, response) {
$.ajax({
url: "get_site2.php",
dataType: "json",
data: {
term: request.term
},
beforeSend: function () { // add this
showLoading("remove");
console.log("remove");
},
success: function (data) {
response(data);
}
});
},
minLength: 2,
select: function (event, ui) {
$("#site_name").val(ui.item.label);
$("#site_id").val(ui.item.name);
return false;
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("ui-autocomplete-item", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
});
I confused, I already search and try this question but it did not fix it.
Sorry this fix might be a bit late .. but for the other guys running into this problem.
just change
}).data("ui-autocomplete")._renderItem = function (ul, item) {
to
})._renderItem = function (ul, item) {
This should resolve the issue.
In some cases it will look like this
.autocomplete().data("uiAutocomplete")._renderItem = function( ul, item )
Change it to
.autocomplete()._renderItem = function( ul, item )
This helped me:
).data().autocomplete._renderItem = function (ul, item) {

jquery autocomplete 'Disable' show all terms

Hey could someone guide me out of this problem....
I successfully created the jquery autocomplete function , but my problem is that autocomplete suggestions shows all the available labels . Autocomplete is showing the results which are not even matching the search term . I mean it showing all available label . Is their any solution to show only matching labels. here is the java function.
Any help will be gladly appreciated . Thank You
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data.stuff, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
EDIT : - Here is the Json File
{"stuff":[ {"label" : "Dragon", "value" : "eg.com"} ,
{"label" : "testing", "value" : "eg2.com"}]}
Successful Edited Code
<script>
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
var re = new RegExp( request.term, "i" );
return re.test( v.label );
});
response( $.map( sData, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
focus: function (event, ui) {
this.value = ui.item.label;
event.preventDefault(); // Prevent the default focus behavior.
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
</script>
Here is the change you want to make:
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
return v.value.indexOf( request.term ) > -1;
});
response( $.map( sData, function ( item ) {
This search will be done by value. To search by label, in other words for the user's input to be compared to the label in your JSON use the following instead:
return v.label.indexOf( ........
UPDATE
To make your search case insensitive, use the following:
var re = new RegExp( request.term, "i" );
return re.test( v.label );
instead of return v.value.indexOf( request.term ) > -1;

jQuery Autocomplete can't replace only part of input value

I am trying to make autocomplete like on Github.
We have a textarea where we write in it some text. We also put -> '#' and try to auto complete a username.
When we the autocomplete script runs it removes all of the text.
My script:
function getSign(text){
var indexOfAt = text.lastIndexOf('#');
return indexOfAt;
};
function changeText(event, ui) {
var selectedElement = event.target.innerText;
var text = $(this).val();
text.replace(/#$/ , selectedElement);
$(this).val(text);
}
$(document).ready(function() {
$("textarea#autocomplite").autocomplete({
source: function(request, response) {
$.ajax({
url: "/feeds/autocomplite_search",
data: {
term: request.term.substr(getSign(request.term)+1,request.term.length-getSign(request.term)).trim()
},
success: function(data){
for(i=0; i<data.length; i++){
data[i] = '#'+data[i];
}
return response(data);
}
});
},
minLength: 2,
delay: 400,
disabled: true,
search: function() {
if ( /\s$/.test($(this).val()) ) {
$(this).autocomplete('disable');
};
},
select: changeText
});
$("textarea#autocomplite").keyup(function() {
if ( /#$/.test($(this).val()) ) {
$(this).autocomplete('enable');
};
});
});
replace does not modify the original. Reassign:
text = text.replace(/#$/ , selectedElement);

Categories

Resources