jquery autocomplete 'Disable' show all terms - javascript

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;

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

jQuery UI Autocomplete - Search based on a json node

I'm trying to search based on a school name, once the school name is selected populate a form.
I'm having a few issues searching on that particular jSON node, which in this case is name I have got the JSON response working, But it's just returning everything back. Not the specific term.
An example of my jSON Data :
[
{
"name":"The Mendip School",
"ta":"ta552023",
"address1":"Longfellow Road",
"address2":"Radstock",
"town":"",
"postcode":"BA3 3AL"
}
]
My jQuery is as follows :
// School Search....
var data_source = 'schools.json';
$(".school_name").autocomplete({
source: function ( request, response ) {
$.ajax({
url: data_source,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data, function ( item )
{
return {
label: item.name,
value: item.name
};
}));
}
});
},
minLength: 3,
focus: function (event, ui) {
$(event.target).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
How do I modify my JQuery to search on the name field? I will also need to get the other fields to populate input fields.
Thanks
Here is something that may suit your needs:
$("#school_name").autocomplete({
source: function ( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
$.getJSON("/schools.json?term=" + request.term, function (data) {
var x = $.grep(data, function (item, index) {
return matcher.test( item.name );
});
console.log(x);
response($.map(x, function (item) {
return {
label: item.name,
value: item.name
};
}));
});
}
The code above will filter the data using the regex(new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" )). This regex will search for names which start-begin(^) with the typed text(by the user). The 'i' in the regex is for case-insensitive while the escapeRegex will just escape any special characters in user input.
You can also use your code and do the respective changes, I think it will also work. I just prefer to use $.getJSON. Take care of the #school_name for id(in your code you are using '.')
Try it here: http://jsbin.com/vawozutepu

How make textbox readonly after filled with autocompleted value using jquery?

Here I've a textbox, its data is filled by autocomplete using JSON.
Here i want textbox readonly after selecting any value of autocomplete (suggested fields).
textbox code:
$(document).ready(function ()
{
$('#patient_id').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'opdpatientajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'patientname',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
console.log(names[1], names[2], names[3]);
$('#patientAddress').val(names[1]);
$('#patientSex').val(names[2]);
$('#patientAge').val(names[3]);
}
});
});
<input type="text" id="patient_id" name="patient_nm"
placeholder="Enter and select Mother Name" title="Please Enter and select patinet name">
$("#patientAddress").attr("disabled", "disabled");
If you want to submit the field to $_POST, you need to enable it before sending the form.
$(document).ready(function ()
{
$('#patient_id').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'opdpatientajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'patientname',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
console.log(names[1], names[2], names[3]);
$('#patientAddress').val(names[1]);
$('#patientSex').val(names[2]);
$('#patientAge').val(names[3]);
$("#patientAddress").attr("disabled", "disabled");
$("#patientSex").attr("disabled", "disabled");
$("#patientAge").attr("disabled", "disabled");
}
});
});
OR you can use this method:
$( "#other" ).click(function() {
$( "#target" ).blur();
});

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

Categories

Resources