I am using JQuery autocomplete to get data from database in php.
I am getting correct result from database as I type keyword. But, I want id of that data separate (because I don't want id in the label itself). My JQUERY CODE lokks like this:
$( "#referrer" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax/ir_populate_referrer",
dataType: "json",
type: "POST",
data: {
keyword: request.term
},
success: function(data){
response( $.map( data, function( item ) {
//alert(item.label);
return {
label: item.label
}
}));
}
})
}
});
PHP Backend:
$searchArray = array();
while($search = $result->fetch()){
$link = '';
$link .= $search['id'].', '.$search['cus_firstname'].' '.$search['cus_lastname'].', '.$search['cus_email'].', '.$search['cus_phone1'];
array_push($searchArray, array('label'=> $link, 'value' => $keyword, 'id'=>$search['id']));
}
echo json_encode($searchArray);
The problem is how can I put id in html other than label itself, when user selects particular suggestion. I want to put id in this HTML container:
<input type='hidden' name='referrer_id' id='referrer_id' />
$( "#referrer" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax/ir_populate_referrer",
dataType: "json",
type: "POST",
data: {
keyword: request.term
},
success: function(data){
response( $.map( data, function( item ) {
//alert(item.label);
return {
label: item.label,
value: item.value // EDIT
}
}));
}
})
}
select: function(event, ui) {
$("#referrer_id").val(ui.item.value); // ui.item.value contains the id of the selected label
}
});
$("#zipsearch").autocomplete({
source: function(req,res) {
$.ajax({
url: "json.php",
dataType: "json",
type: "GET",
data: {
term: req.term
},
success: function(data) {
res($.map(data, function(item) {
return {
label: item.label,
value: item.value,
id: item.id
};
}));
},
error: function(xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
},
focus: function( event, ui ) {
$( "#zipsearch" ).val( ui.item.label );
return false;
},
select: function(event, ui) {
alert(ui.item.id);
$( "#zipsearch" ).val( ui.item.label );
return false;
}
});
<head runat="server">
<title></title>
<link href="Styles/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui.js" type="text/javascript"></script>
<style>
body
{
font-size: 70%;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/AutoCompleteAjaxRequest",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'prefixText' : '" + $("#<%=TextBox1.ClientID %>").val() + "'}",
success: function (data) {
response($.map($.parseJSON(data.d), function (item) {
return {
label: item.UserNameToShow,
value: item.UserName,
id: item.UserId
}
}))
}
});
},
select: function (event, ui) {
$("#referrer_id").val(ui.item.id); // ui.item.value contains the id of the selected label
}
});
});
</script>
Related
i used jqueryui autocomplete iwant be the same work for some input text
but when i use $(this).val() for send value of textbox it show error and when i use (".Degree").val() shows and send to server first textbox it incorrect
function DegreeAutoComplete() {
$(".Degree").autocomplete({
position: { my: "right top", at: "right bottom", collision: "none" },
source: function (request, response) {
var spin = $(".spinnerDegree");
spin.addClass("fa-spin fa-spinner");
$.ajax({
url: "#Url.Action("GetDegree")",
type: "POST",
dataType: "json",
data: { search: $(".Degree").val() },
success: function (data) {
spin.removeClass("fa-spin fa-spinner");
response($.map(data, function (item) {
return { label: item.PersianName, value: item.PersianName, id: item.Id };
}));
}
});
},
messages: {
noResults: '',
results: function (resultsCount) { }
},
select: function (event, ui) {
// ui.item.value contains the id of the selected label
alert($(this).val());
$(this).attr("sel", ui.item.id);
}
});
}
when i use: $(this).val();
elem.nodeName is undefined
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[elem.nodeName.toLowerCa...
how can i fix it
this refers to ajax object inside it. Save this reference before using it in inside scope.
var spin = $(".spinnerDegree");
spin.addClass("fa-spin fa-spinner");
var $that = $(this);// save reference
$.ajax({
url: "#Url.Action("
GetDegree ")",
type: "POST",
dataType: "json",
data: { search: $that.val() },//use $that var here
success: function(data) {
spin.removeClass("fa-spin fa-spinner");
response($.map(data, function(item) {
return { label: item.PersianName, value: item.PersianName, id: item.Id };
}));
}
});
EDIT:
Just checked jquery UI doc
You should use request.term thats it.
source: function(request, response) {
$.ajax({
url: "#Url.Action("GetDegree")",
type: "POST",
dataType: "json",
data: {
search: request.term
},
success: function(data) {
//....
}
});
}
i use jquery for create an autocomplete for a textbox, data fetches from an an asmx webservice. i monitor my code on firebug ,this tool shows request sent and xml response recieved . but autocomplete not open for textbox :(
Could someone please tell me why my code for the jquery autocomplete is not working?
jquery code:
<link href="../Script/MainCSS.css" rel="stylesheet" />
<link href="../Script/jquery-ui.css" rel="stylesheet" />
<script src="../Script/jquery-1.10.2.js"></script>
<script src="../Script/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$('.textBox').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Services/BusService.asmx/GetRouteInfo",
data: { param: $('.textBox').val() },
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message)
// console.log("Ajax Error!");
}
});
},
minLength: 2 //This is the Char length of inputTextBox
});
});
</script>
my c# code:
[WebMethod]
public string[] GetRouteInfo(string param)
{
List<string> list_result = new List<string>();
AutoTaxiEntities useEntity = new AutoTaxiEntities();
System.Data.Entity.Core.Objects.ObjectResult<DAL.Model.SP_FIND_ROUTE_ROUTESTOPS_Result> sp_result = useEntity.SP_FIND_ROUTE_ROUTESTOPS(param);
foreach (DAL.Model.SP_FIND_ROUTE_ROUTESTOPS_Result sp_result_item in sp_result.ToList())
{
list_result.Add(sp_result_item.ID + "," + sp_result_item.ITEMTYPE + "," + sp_result_item.TITLE);
}
return list_result.ToArray();
}
Looking at your added script references, i think you have not added autocomplete.js script. Please add it and try it once.Please click here
$(document).ready(function () {
$('#<%=txtSearch.ClientID%>').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: "/Services/BusWebService.asmx/GetRouteInfo",
data: "{ 'param': '" + request.term + "' }",
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
itemid: item.split(',')[0],
itemtype: item.split(',')[1],
label: item.split(',')[2]
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (event, ui) {
$('#<%=hfItem.ClientID%>').val(ui.item.itemid + ',' + ui.item.itemtype + ',' + ui.item.label);
//$("form").submit();
}
});
});
I try to write jQuery script with autocomplete, and select correct value on the client side.
My working code without selected value (it give me all username available in my json):
$(function() {
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://127.0.0.1/json.php",
dataType: "json",
data: {
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function(data) {
response($.map(data.employee, function(item) {
return {
label: item.username,
};
}));
}
});
},
minLength: 2,
select: function(event,ui) {
$('#users').val(ui.item.username);
}
});
But when I try to add selector, how in this example.
My code:
$(function() {
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://127.0.0.1/json.php",
dataType: "json",
success: function(data) {
var re = $.ui.autocomplete.escapeRegex(request.term);
var matcher = new RegExp( "^" + re, "i" );
response($.grep($.map(data.employee, function(item){
return {
label: matcher.test(item.username),
}
})));
}
});
},
minLength: 2,
select: function(event,ui) {
$('#users').val(ui.item.username);
}
});
});
I get an error:
TypeError: callback is not a function jquery-1.10.2.js:762
What am I doing wrong?
P.S. my json:
{"employee":[{"username":"username1","placeId":"505B-D","subordinates":["username2","username3"]},{"username":"username4","placeId":"505B-A","subordinates":["username5","username6"]}]}
If you want use grep and map together, you can write something like this:
function() {
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://172.18.128.186/json.php",
dataType: "json",
success: function(data) {
var re = $.ui.autocomplete.escapeRegex(request.term);
var matcher = new RegExp( "^" + re, "i" );
var g = $.grep(data, function(item){return matcher.test(item.username);});
response($.map(g, function(item){return {label: item.username,}}));
}
});
},
minLength: 2,
select: function(event,ui) {
$('#users').val(ui.item.username);
}
});
I am using Jquery autocomplete with ajax.
Everything works fine except when I set minLength to 0.
When I choose an element from the list, the autocomplete doesn't stop running and shows me the list again.
Here is the code:
$("#id_from").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://127.0.0.1:8000/core/get_from_cities",
dataType: "json",
data: {term: request.term},
success: function (data) {
response($.map(data.data, function (item) {
return {
label: item.value,
value: item.value
}
}));
}
});
},
minLength: 0
});
Thanks..
EDIT:
Here is the solution I came up with:
$("#id_to").focus(function() {
$( "#id_to" ).autocomplete( "enable" );
});
$("#id_ffrom").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://127.0.0.1:8000/core/get_from_cities",
dataType: "json",
data: {term: request.term},
success: function (data) {
response($.map(data.data, function (item) {
return {
label: item.city,
value: item.city,
}
}));
}
});
},
minLength: 0,
select: function (event, ui) {
$('#id_from_country').val(ui.item.country)
$("#id_ffrom").autocomplete( "disable" );
}
});
I now have a working JavaScript autocomplete function, thanks to help from many of you. Now I want to make the function reusable. There are three variables that need to be specified for each instance of the function, as shown below. What I don't know how to do is instantiate this function with different values for these three vars.
Here is my HTML field:
<div class="ui-widget">
Text or Value:
<input type="text" id="dotmatch" />
</div>
And here is the JavaScript code which I want to keep in its own .js file:
var matchFieldName = 'dotmatch';
var resultFieldName = 'dotnumber';
var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList";
$(function() {
$('#' + matchFieldName).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
label: item.Label + "(" + item.Value+ ")",
value: item.Value
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
return ui.item.label;
}
});
});
insin was close. The solution I worked out this morning is;
function AutoComplete(matchFieldName, resultFieldName, lookupURL) {
$('#' + matchFieldName).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
value: item.Value,
label: (item.Label == item.Value) ? item.Label : item.Label + "(" + item.Value + ")"
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
}
});
}
On the web page:
<div id="AutoSuggest">
DOT Job Title or Number:
<input type="text" id="dotmatch" style="width:300px;" />
</div>
And on the web page, after the tag:
<script type="text/javascript" src="js/DOTAutocomplete.js"></script>
<script type="text/javascript">
$(function() {
AutoComplete("dotmatch", "dotnumber", "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList");
});
</script>
It looks like you're using jQuery, so you might want to implement it as a plugin.
(function($) {
$.fn.bobsAutocomplete = function(resultFieldName, lookupURL) {
this.autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({prefixText: request.term, count: 20}),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
label: item.Label + "(" + item.Value+ ")",
value: item.Value
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
return ui.item.label;
}
});
return this;
};
})(jQuery);
Usage:
$("#dotmatch").bobsAutocomplete("dotnumber", "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList");