I use the jQuery UI autocomplete fetching data from a Postgresql-database to populate an input-box (parzelle) with label-data. My form then submits the corresponding value-data, stored in a hidden input (gid).
My code works when the page is loaded the first time, sometimes even, when the page is reloaded after submitting the form. In most cases the autocomplete stops working after the first reload of the (same) page.
I use a quite simple modification of the example provided by jQuery UI:
$( "#parzelle" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "./mapdata/get_parzellen_list_json.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
} );
},
minLength: 3,
select: function( event, ui ) {
// prevent autocomplete from updating the input-box (parzelle)
event.preventDefault();
// update the input-box and hidden input (= gid)
$(this).val(ui.item.label);
$("#gid").val(ui.item.value);
}
} );
Related
I am in the biggest problem
**PLEASE DONT REPORT MY QUESTION DUPLICATE BECAUSE I DID NOT GET ANSWER FOR ASP.NET IN GOOGLE.
I am using jquery Autocomplete textbox in asp.net using web service.
my code
$('input.txtE').autocomplete({
source: function (request, response) {
$.ajax({
url: "WebServices.asmx/GetNames",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txtInput' : '" + request.term + "','userName':'" + userName + "'}",
dataFilter: function (data) { return data; },
success: function (data) {
mydata = data.d;
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}))
},
error: function (result) {
alert("Error");
}
});
},
multiselect: false,
minLength: 1,
delay: 0,
select: function (e, ui) {
$(hfId).val(ui.item.val);
}
});
<input type="hidden" id="hfId"/>
And my API return data in array format
["Abhishek/128", "Abyss/71", "athansiah/53", "blvsian/138", "DesmondH/91", "destined2hold/62", "dnbdesigns/94", "Dvus_lotus/85", "gserranof/47", "Illusions/89", "isaacwu111/111", "js/39"]
What I need if a user selected remove him from the autocomplete list so we can't select him again.
Please help me to short out it.
Preparation
In first, you need to store setected values. It is possible by using a global variable, hidden input control or arbitrary data associated with your control. In the following example I create an array that is associated with autocomplete control and then store selected values to the array:
$('#my-control').autocomplete({
create: function( e, ui ) {
// initialize array
$(this).data('selected', []);
},
select: function( e, ui ) {
// store unique selected values
var selected = $(this).data('selected');
if(!~selected.indexOf(ui.item.value)) {
selected.push(ui.item.value);
}
},
// another options here
});
Now it is possible to consider the selected values for list filtering.
Server-side solution
The best way is to filter the list on API server side, because it reduces transferred data amount. Just send the stored values through an AJAX request, using data option:
var $control = $('#my-control');
$control.autocomplete({
source: function (request, response) {
$.ajax({
// some AJAX options
data: {
term: request.term,
selected: $control.data('selected') // send stored values
}
});
},
// some autocomplete options here
});
Then you have to implement server-side filtration in accordance to selected query string parameter.
For example
public class AutocompleteSourceController : ApiController
{
[HttpGet]
public JsonResult<IEnumerable<MyClass>> GetItems(
[FromUri]string term,
[FromUri]int[] selected)
{
// Load data
// Fliter by term substring
// Exclude selected items
// Return the result
}
}
Client-side solution
Another way is to filter responded list on client side, using success AJAX callback. In my example I will use fake online REST API server. The server ignores the term field of query string, so I also have to implement it on client-side.
$control = $('#my-input');
$control.autocomplete({
create: function(e, ui) {
$(this).data('selected', []);
},
source: function(request, response) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
var items = data
// filter by term
.filter(function(user) {
return ~user.name.toLowerCase().indexOf(request.term.toLowerCase());
})
// exclude stored selected values
.filter(function(user) {
return !~$control.data('selected').indexOf(user.id);
})
// cast to an objects with label and value properties
.map(function(user) {
return {
label: user.name,
value: user.id
}
});
response(items);
},
error: function(result) {
alert("Error");
}
});
},
multiselect: false,
minLength: 1,
delay: 0,
select: function(e, ui) {
e.preventDefault();
$ctrl = $(this);
var selected = $control.data('selected');
if (!~selected.indexOf(ui.item.value)) {
// store selected value
selected.push(ui.item.value);
// set label instead of value
$ctrl.val(ui.item.label);
}
},
});
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<input id="my-input" type="text">
Type L to the input control. The first item will be Leanne Graham, select it. Then clean the input field and type L again, there will no Leanne Graham in the dropdown menu. Select Ervin Howell, then clean the input field and type L again. There will be neither Leanne Graham nor Ervin Howell in the dropdown menu.
If you want to consider only current selected value, you could store only latest value instead of an array and modify the success callback and the select event handler.
Try to remove selected value from array using jQuery.
x = jQuery.grep(x, function(val) {return val != Item;});
I am using autocomplete j query to suggest my users some questions and then when user select one of the questions it should shows the answer.
it works fine for the first click
when user clicks on each of these questions the answer is showing correctly but the problem is when user clear the inputs and write another word and then select one of the suggestion for the next time nothing happened after select each one
here is my jquery codes
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
dataType: 'json',
method: 'POST',
data: {
q: request.term
},
url: 'Help_And_Customer_Support/AjaxQuestion/q',
success: function (data) {
console.log(data.Qu);
response($.map(data, function (item) {
console.log(item.Ans);
return { label: item.Qu, id: item.Ans };
}))
},
});
},
select: function (event, ui) {
$("#showansw").css("height", 200);
var qans = ui.item.id;
var qq = ui.item.label;
$("#showansw p").html(qans);
$("#showansw h5").html(qq);
}
});
Appreciate any help. thanks
I'm using the JqueryUI autocomplete. Sometimes the fetching of results isn't immediate so I'd like to notify the user the autocomplete is fetching options that match his query.
My Code:
$( "#searchid" ).autocomplete({
source: "/autocomplete_url.php",
minLength:3,
select: function(event, ui) {
event.preventDefault();
$("#searchid").val(ui.item.value);
$("#formid").submit();
}
});
How can I make the autocomplete to open a 'fetching results status bar' when sending a request to the web-service that is working on finding the results?
This approach assumes you're using an Ajax call to retrieve your dataset, but I've used something similar and it worked ok.
Set up a div on the page where you want the message.
HTML:
<div id="AutocompleteStatus" style="display:none">Loading data...please wait</div>
You then want to catch the key up event on your autocomplete:
jQuery:
$( "#searchid" ).keyup(function() {
$('#AutocompleteStatus').show();
});
Then your autocomplete could look something like this:
$( "#searchid" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/autocomplete_url.php",
dataType: "json",
data: {
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
$("#AutocompleteStatus").hide(); // <== HIDE IT HERE
response( $.map( data.returndata, function( item ) {
return {
label: item.name,
value: item.value
}
}));
}
});
}, minLength:3,
select: function(event, ui) {
event.preventDefault();
$("#searchid").val(ui.item.value);
$("#formid").submit();
}
});
So the short version: Key up on your search box shows the div, on the return from your Ajax call (I'm using sample parameter names, your example didn't give any actual names), just hide the div again.
I'm using Jquery UI's autocomplete, and I can see the proper JSON data coming back in Firebug. However, nothing's coming back to the textbox.
My JavaScript:
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
}
$("#tags").autocomplete({
source: function(request, response){
$.ajax ({
url: "/projectlist",
dataType: "json",
data: {style: "full", maxRows: 12, term: request.term}
});
}
})
});
You can see that from the snippet JSON data is being returned. But nothing is being displayed in the results table. Which should look like the the JQuery autocomplete example JQuery Autocomplete
Noyhing is displayed because you return nothing i think: you must add e success function to your ajax call (i added an example of a success response, if you tell us how your json is tructured i could help you better. in any case you must return an array of objects, and each object should have a property named 'label' and one named 'value':
$("#tags").autocomplete({
source: function(request, response) {
$.ajax({
url: "/projectlist",
dataType: "json",
data: {
style: "full",
maxRows: 12,
term: request.term
},
success: function(data) {
var results = [];
$.each(data, function(i, item) {
var itemToAdd = {
value: item,
label: item
};
results.push(itemToAdd);
});
return response(results);
}
});
}
});
I set up a fiddle here: http://jsfiddle.net/nicolapeluchetti/pRzTy/ (imagine that 'data' is the json that is returned)
I am trying to use jquery-ui for autocompletion in a search field. Because the search depends on the value of another form field, I'm using a callback for the source. I can see that the request is sent correctly. My remote script returns a simple array of strings and it's at that point that I can't get it to work. The dropdown list is never built. Can anyone tell me why? Here's the code:
$(document).ready(function(){
$("#species").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/includes/species-ajax.cfm",
dataType: "jsonp",
data: {
term: request.term,
searchBy : function() {
var sb = $("#searchBy_hidden").val();
return (sb ? sb : 'common_name'); }
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.name,
value: item.name
}
}));
}
});
}});
});
<input type="hidden" name="searchBy_hidden" id="searchBy_hidden" value="common_name" />
Enter the name of a species: <input type="textbox" size="30" id="species" />
Thanks,
Try changing your dataType to 'json', not 'jsonp'