Always show autocomplete list, even if search doesn't match - javascript

I have an autocomplete field, and on type I go to the PHP/Database to retrieve the matching options.
Thing is, my suggestion list isn't exactly matches of the text. I explain:
Say I type "Jon". My list will bring from the database "John Doe", "Jonatan", etc. Only "Jonatan" will be visible as the suggestion to the input, but I do need them all, because it considers approximation (there's a soundex element on my backend search).
My JavaScript/Ajax code:
function prePatientsList(){
//I'm limiting search so it only starts on the second character
if (document.getElementById("name").value.length >= 2) {
try
{
listExecute.abort();
}catch(err) {
null;
}
var nome= $("#name").val();
var nomeList = "";
listExecute = $.ajax({
url: '/web/aconselhamento/Atendimento/PrePacientesAutocomplete',
type: "POST",
async: true,
datatype: 'json',
data: { nome: nome}
}).done(function(data){
source = JSON.parse(data);
});
$(function() {
$("input#nome").autocomplete({
source: source,
// I know I probably don't need this, but I have a similar component which has an URL as value, so when I select an option, it redirects me, and I'll apply you kind answer on both.
select: function( event, ui ) {
ui.item.label;
}
});
});
}
}
Thanks.

I think you'd have to set your remote endpoint directly as the autocomplete's source (e.g. similar to https://jqueryui.com/autocomplete/#remote) so that it's the backend which does all the filtering. Right now, the autocomplete effectively thinks you've fed it a static list of options from which further filtering should take place, and therefore it decides to handle the filtering itself.
Your code can be as simple as this I think, no need to have a separate handler or an ajax request outside the scope of the autocomplete.
$(function() {
$("input#nome").autocomplete({
minLength: 2, //limit to only firing when 2 characters or more are typed
source: function(request, response)
{
$.ajax({
url: '/web/aconselhamento/Atendimento/PrePacientesAutocomplete',
type: "POST",
dataType: 'json',
data: { nome: request.term } //request.term represents the value typed by the user, as detected by the autocomplete plugin
}).done(function(data){
response(data); //return the data to the autocomplete as the final list of suggestions
});
},
// I know I probably don't need this, but I have a similar component which has an URL as value, so when I select an option, it redirects me, and I'll apply you kind answer on both.
select: function( event, ui ) {
ui.item.label;
}
});
});
See http://api.jqueryui.com/autocomplete/#option-source for more info.

Related

How to Trigger JQuery with AJAX Autocomplete

I've seen some similar posts here, but unfortunately none of them have solved my problem. My experience with JQuery is minimal, so I'm sure there's something I'm missing. If someone could help me with this, I'd really appreciate it!
I created an ASP.NET/C# page that uses a JQuery/AJAX autocomplete function to display a list of tag or lot numbers the user can select from as they type values in a textbox (txtLookup).
$(document).ready(function ()
{
$("#txtLookup").on("keyup",function () {
var textCheck = $("#txtLookup").val();
if ($("#txtLookupType").val() == "tagNo")
{
$(".autosuggest").autocomplete(
{
source: function (request, response) {
$.ajax(
{
type: "POST",
url: "Inventory.aspx/GetAutoCompleteData",
data: '{"lookup":' + textCheck + '}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) { response(data.d); },
});
}
, minLength: 2,
});
}
else if ($("#txtLookupType").val() == "lotNo")
{
var jsonText = JSON.stringify({ lookup: textCheck + '%' });
$(".autosuggest").autocomplete(
{
source: function (request, response) {
$.ajax(
{
type: "POST",
url: "Inventory.aspx/GetAutoCompleteData3",
data: jsonText,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) { response(data.d); },
//error: function (ts) { alert(ts.responseText); }
});
}
, minLength: 2,
});
}
else
{
}
});
});
The function works great when a keyboard is used to enter the values, but users can also enter numbers via an on-screen number pad I created (the program runs on a touchscreen). When users click a number button, the number is written to the textbox via Javascript. I'd like to trigger the autocomplete at this time, but I can't figure out how to do it. Some of the things I've tried are commented in the code block below. I've also tried modifying the function to use $("[id$=txtLookup").keyup(function () { instead of $("#txtLookup").on("keyup",function () {. I've tried different events, like keydown, keypress, and change, but haven't had any luck. ​
This Javascript block runs when the user clicks the "1" button:
if (object.id == "imgNum1")
{
var x;
x = "1";
var textObj = document.getElementById('txtLookup');
insertTextAtCursor(textObj, x);
document.getElementById("txtLookup").focus();
document.getElementById("txtLastClickedBtnValue").value = '';
//Failed attempts...
//$("#txtLookup").trigger("keyup");
//jQuery(document).ready(function(){});
//$(".autosuggest").autocomplete("search");
//$("input#txtLookup").autocomplete("search");
//$("[id$=txtLookup]").autocomplete("search");
}
Can someone please tell me what I'm doing wrong? Thanks in advance!
Edited to add the ASP.NET code:
Textbox:
<asp:TextBox id="txtLookup" runat="server" Height="16px" Width="155px" CSSClass="labelAlignTop autosuggest" onfocus="javascript: setTextboxID(this);"></asp:TextBox>
The setTetboxID function just writes the textbox name to a hidden field to store it to track the last clicked textbox.
Number button:
<asp:ImageButton ID="imgNum1" ImageUrl="Images/InvNumPad/btn_1.png" runat="server" onmouseover="this.src='Images/InvNumPad/btn_1_Over.png'" onmouseout="this.src='Images/InvNumPad/btn_1.png'" CssClass="inv_btnNum1" onfocus="javascript: getButtonClicked(this)" onclientclick="return false;" Width="50px" Height="50px"/>
The getButtonClicked function contains the Javascript block I posted above that runs when the user clicks the "1" button and handles the caret positioning.
After much fiddly work, Divine intervention blessed me with the solution to my question. I wanted to add an update in case someone in the future is tearing their hair out looking for the answer. To trigger the autocomplete code I posted above, I needed to trigger two events: touchstart and input.
function triggerAC()
{
//Triggers txtLookup autocomplete after touchscreen event
$("#txtLookup").trigger("touchstart");
$("#txtLookup").trigger("input");
}
I also added touchstart to the third line of the code block I originally posted, changing
$("#txtLookup").on("keyup",function () {
to
$("#txtLookup").on("keyup touchstart",function () {

Add extra data in textextjs plugin

I'm trying to call a funtion in textextjs method-
//my function
function GetAreaTags() {
return "some text";
}
//textext initializtion
$('#territory').textext({
plugins: 'tags prompt focus autocomplete ajax',
ajax: {
url: '/Admin/Search/GetTerritorySuggestions?area=' + GetAreaTags(),
dataType: 'json',
cacheResults: false
}
});
But GetAreaTags() is not being called. How can i make it happen?
It should work... But try this:
function GetAreaTags() {
return "some text";
};
var yourObj= {
plugins: 'tags prompt focus autocomplete ajax',
ajax : {
url: '/Admin/Search/GetTerritorySuggestions?area=' + GetAreaTags(),
dataType: 'json',
cacheResults: false
}
};
$('#territory').textext(yourObj);
console.log(yourObj.ajax.url);
If that doesn't work out try this:
function GetAreaTags() {
return "some text";
};
var yourObj= {
plugins: 'tags prompt focus autocomplete ajax',
ajax : {
url: function() {return '/Admin/Search/GetTerritorySuggestions?area=' + GetAreaTags()},
dataType: 'json',
cacheResults: false
}
};
$('#territory').textext(yourObj);
console.log(yourObj.ajax.url);
Check the console both times to see if your url is what you desire.
[EDIT: I rejected the edit by mistake, sorry about that]
Edit2
From s.k.paul's comment:
GetAreaTags() should execute every time i type in that textbox.
However, console says- 1. /Admin/Search/GetTerritorySuggestions?area=
2. localhost:12788/Admin/Dashboard/…}&q= 404 (Not Found)
Therefore you need another event handler to dynamically change the url (the plugin must be recalled with another url):
function GetAreaTags() {
return "some text";
};
$("#territory").keyup(function() {
var yourObj= {
plugins: 'tags prompt focus autocomplete ajax',
ajax : {
url: function() {return '/Admin/Search/GetTerritorySuggestions?area=' + GetAreaTags()},
dataType: 'json',
cacheResults: false
}
};
$('#territory').textext(yourObj);
console.log(yourObj.ajax.url);
});
However, this may be very heavy... The plugin expects you to have a single reference for your auto-complete resource. If you're dynamically changing it, it may reset the already existing stuff.
Edit3
Edit 2 : textextjs does not work at all now. And, url function returns
whole function text
This means the plugin doesn't handle well being recalled twice or more times in the same element. The only possible solution I am seeing is to change the plugin's code in order to dynamically change the resources according to your function...
Which makes me wonder, if it's easier for you to allow the user to have a broader data resource (include all areas) when typing, this way there would be only one URL and the plugin wouldn't have any trouble with that.

jquery Select2 prevent selecting in ajax response

I want to prevent from adding a category to the Select2 element if it fails creating the row first in my db. The action is not prevented when i call ev.preventDefault(); Nothing happens.. what is wrong?
$('#sel2').select2({
placeholder: 'Enter categories',
minimumInputLength: 3,
multiple: true,
ajax: {
url: 'async/get_categories.php',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
q: term,
};
},
results: function (data, page) {
return {
results: data.items
};
},
cache: true
},
formatResult: format,
formatSelection: format
}).on('select2-selecting', function(e) {
console.log(e);
if (e.val == 4) {
// if category id equals 4
// do not add this category to select 2
// e.preventDefault();
// the above works just fine and its just for testing
}
// Is something wrong here?
var ev = e;
$.ajax({
type: 'POST',
url: 'async/create_profile_category.php',
data: {
profile_id: '1',
category_id: ev.val
},
success: function(response) {
console.log(response);
if (response.error === false) {
// category assigned successfully
} else {
// failed to assign category
// so i want now to prevent from adding to select2
console.log('should not add this category');
ev.preventDefault();
// the above is not working
}
},
error: function() {
alert('Failed to assign category!');
}
});
});
The AJAX request is made asynchronusly, so by the time it has finished the element has already been added. Even though you are calling ev.preventDefault(), it is too late for it to make a difference. So this leaves you with two options:
Make the request synchronusly, which will allow preventDefault to make the difference.
Make the request asynchronusly, and manually remove the element if it fails.
Both options have their pros and cons, and it's up to you to decide which option you go with.
Making the request synchronusly
Pros
The value will never be added if the request fails.
Works well in cases where the element cannot be added quite often.
Cons
Blocks the UI - So the user is potentially left with an unresponsive page while the request is made.
Making the request asynchronusly
Pros
Does not block the UI.
Works well in cases where elements typically can be added.
Cons
The value will always show up for the user, even if it fails later.
You must manually unset the new option.
What's important to consider here is the user experience of both options. When making synchronus requests, it's not uncommon for the browser to stop relaying events - which gives the illusion that the UI has locked up and the page has gone unresponsive. This has the benefit of ensuring that the value never shows up if it isn't allowed. But if users typically can add the elements, it also has the downside of complicating the most common use case.
If users can usually add elements, then it is a better experience to add the element while the request is being made, and then notifying the user later (while removing the element) if there was an issue. This is very common is web applications, and you can see it being used in many places, such as the Twitter and Facebook like buttons (where requests usually work), as well as places on Stack Overflow.
There is a way to get around this with version4 of the select2 library.
on select2:selecting we cancel the preTrigger event. Which will stop the select2:select event. We do our ajax call. On success we then get out Select2 instance then call the trigger of the Observer that way it by passes overwritten trigger method on your select2 instance.
The call method needs your select2 instance as the context so that the existing listeners are available to call.
var sel = $('#sel');
sel.select2(config);
sel.on('select2:selecting', onSelecting);
function onSelecting(event)
{
$.ajax({
type: 'POST',
url: 'async/create_profile_category.php',
data: {
profile_id: '1',
category_id: event.params.args.data.id
},
success: function(event, response) {
console.log(response);
if (response.error === false) {
// category assigned successfully
// get select2 instance
var Select2 = $users.data('select2');
// remove prevented flag
delete event.params.args.prevented;
// Call trigger on the observer with select2 instance as context
Select2.constructor.__super__.trigger.call(Select2, 'select', event.params.args);
} else {
// failed to assign category
// so i want now to prevent from adding to select2
console.log('should not add this category');
}
}.bind(null, event),
error: function() {
alert('Failed to assign category!');
}
});
event.preventDefault();
return false;
}
here how I did it for yii2 Select2 integrated into Gridview:
'pluginEvents' => [
'select2:selecting' => "
function(event)
{
var select2 = $('#types-" . $model->id . "');
select2.select2('close');
$.post('update',{id: " . $model->id . ", type_id: event.params.args.data.id})
.done (function(response)
{
select2.val(event.params.args.data.id);
select2.trigger('change');
})
.fail(function(response)
{
krajeeDialog.alert('Error on update:'+response.responseText);
});
event.preventDefault();
return false;
}",
],
it allows to asynchoronous update data in the grid using select2 and ajax and return it to previous value if there was an error on updating.

JQuery AutoComplete not displaying

I have used JQuery UI autocomplete to cut down on the list of parts I have to display in a drop down, I am also using json to pass the list of parts back but I am failing to see the results, I am sure this is to do with my limited understanding of JQuery's Map function.
I have the following json
{"parts":[{"partNumber":"654356"},{"partNumber":"654348"},{"partNumber":"654355-6"},{"partNumber":"654355"},{"partNumber":"654357"},{"partNumber":"654357-6"},{"partNumber":"654348-6"}]}
which on JSONLint is validated correct
I have viewed the post and response utilising Firebug and seen them to be correct but my auto complete does not seem to display, the closest I have got it to doing so, was when I displayed the entire JSON string with each character having a new line.
here is my JS
$('.partsTextBox').autocomplete({
minLength: 3,
source: function(request, response) {
$.ajax({
url: './PartSearch.ashx',
data: $('.partsTextBox').serialize(),
datatype: 'JSON',
type: 'POST',
success: function(data) {
response($.map(data, function(item) {
return { label: item.partNumber }
}))
}
});
},
select: function(e) {
ptb.value = e;
}
});
Any help anyone can give would be much appreciated. Have edited to include help given by soderslatt
I'm not sure, but shouldn't parts.part be an array ?
http://jsfiddle.net/jfTVL/3/
From the jQuery autocomplete page:
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.
Which means that if you use "value" instead of "partNumber", you should get want you want.
jquery autocomplete plugin format out have to
{"query":"your_query","suggestions":["suggestions_1","suggestions_2"],"data":[your_data]}}
and use autocomplete that
$('#your_input').autocomplete({
minChars: 2
, serviceUrl: './PartSearch.ashx'
, deferRequestBy: 50
, noCache: true
, params: { }
, onSelect: function(value, data) {
}
, ajaxCallBack: function() {
response($.map(data, function(item) {
return { label: item.partNumber}
}))
}
});

problem with jquery ui`s autocomplete select callback (1.8)

With this code:
function setupRow(event, ui) {
var textbox, // how do i get to the textbox that triggered this? from there
// on i can find these neighbours:
hiddenField = textbox.next(),
select = textbox.parents('tr').find('select');
textbox.val(ui.item.Name);
hiddenField.val(ui.item.Id);
$.each(ui.item.Uoms, function(i, item){
select.append($('<option>' + item + '</option>'));
});
return false;
}
function setupAutoComplete(){
var serviceUrl = "/inventory/items/suggest";
$("input.inputInvItemName").autocomplete({
source: function(request, response) {
$.ajax({
url: serviceUrl,
data: request,
dataType: "json",
success: function(data) {
response($.map(data.InventoryItems, function(item) {
return {
value: item.Name
};
}));
},
select: function(event, ui) {
setupRow(event, ui);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 3,
delay: 500
});
}
everything seems ok. Problem is the select handler never fires, not even the anonymous function that wraps my original delegate setupRow for debugging purposes is ever called.
anyone can see my error?
I also left a question in the comment: how do I get to the textbox that had the autosuggestion. Cannot use id here, because these text boxes are multiples and generated on the fly, interactively. Or is there another way to do the same thing?
Thanks for any help!
OP point of view
var textbox, // how do i get to the textbox that triggered this? from there
// on i can find these neighbours:
My Point of view
have you tried,
var textbox = $(event.target);
or you can do this,
OP point of view
select: function(event, ui) {
setupRow(event, ui);
},
My point of view
select: setupRow;
then
var textbox = this; // just a guess... wait..
anyone can see my error?
I think you forgot to put ';' .
$.ajax({
url: serviceUrl,
data: request,
dataType: "json",
success: function(data) {
response($.map(data.InventoryItems, function(item) {
return {
value: item.Name
}
}));
Or is there another way to do the same thing?
I think u are using the jquery ui autocomplete plugin.If yes, you can retreive like this.
$('.ui-autocomplete-input')
Otherwise, you can set a specific class to those textboxes and access those textbox through that class.
ok, got a step closer by using
inputs.bind("autocompleteselect", setupRow);
now setupRow fires.
Now it seems, that the success callback transforms the data, I get returned.I need to find a way, to both display the right value in the dropdown, without destroying the requests response...
Any ideas?

Categories

Resources