jquery autocomplete, how to show all options on focous? - javascript

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", "");
});

Related

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.

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;

How to close autocomplete dropdown on side click

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();
}
});

JQUERY autocomplete working in chrome and firefox but not working in IE

I am using a variable from a function to create a autocomplete functionality, here is the code:
function autocomplete(mp_info){
var request_data = {
'_action': 'GET'
};
$(mp_info).find("#id_mp_element").autocomplete({
source: function( request, response, elems ) {
alert("working");
$.ajax({
url: "/api/slots/"+request.term+"/12/",
dataType: "json",
type: 'POST',
data: request_data,
success: function( data ) {
response($.map(data, function(item) {
return {
label: item.name,
id: item.id,
pos: item.position
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
var info_row = $(".info_row").has(this);
$($('td',info_row.parent().prev())[2]).text($(".info_row #id_mp_element").val()+" / "+ui.item.pos);
$("#id_mp_s").val(ui.item.id);
$("#id_mp_position_metric").val(ui.item.pos);
},
});
}
The alert message it is not shown in IE, when we write something in the text input
remove coma at the end:
select: function( event, ui ) {
var info_row = $(".info_row").has(this);
$($('td',info_row.parent().prev())[2]).text($(".info_row #id_mp_element").val()+" / "+ui.item.pos);
$("#id_mp_s").val(ui.item.id);
$("#id_mp_position_metric").val(ui.item.pos);
} <------- there shouldn't be a come here
});

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