autocomplete to populate all values on input focus - json

I have autocomplete textbox whose values are populated using ajax call which returns json data. This works fine with following code lines.
$("#searchTitle").autocomplete({
source: function (request, response) {
$.ajax({
url: "/umbraco/Surface/MyApp/StartSearch",
type: "POST", dataType: "json",
data: { term: request.term },
success: function (data) {
debugger
response($.map(data, function (item) {
debugger
return { label: item.Cat_Name };
}));
}
});
},
messages: { noResults: "", results: "" },
minLength: 0
});
But this function gets called when user type something. Now, I want that when input is focused, all the values from response should be shown in autocomplete. How can I trigger the same?

You can achieve by using search event of autocomplete on focus of input.
For example
$( "#searchTitle" ).focus(function() {
// make sure you put space between double quote
$( "#searchTitle" ).autocomplete("search", " " );
});

Related

Populate textbox with ajax call to server

I have first and last name text boxes, last name on blur triggers an ajax call to get additional data to fill in other textboxes. The call is made and I can see in the Chrome dev tool (network tab) that a json string is coming back with all the data, but I can't figure out how to populate the text fields.
ajax function:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
returns something like this:
{"EmployeeId":0,"FirstName":"Bob","LastName":"Smith","EmailAddress":null,"ManagerEmail":"Boss.Man#work.org","ManagerId":null,"ManagerFirst":"Boss","ManagerLast":"Man"}
The 'alert' shows "undefined".
You may just have a typo. Try changing "datatype" to "dataType"
You are trying to alert a data member of the response string, which does not exist. Instead, you should try to convert the string to object, like this:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
//converting it to object, since further rows expect this
data = $.parseJSON(data);
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
EDIT:
As Bryan Lewis pointed out, it was a typo. This has led to the behavior about which I have written my answer.
Turns out the problem was the server was returning an array of employee objects, so had to access it like:
data[0].ManagerFirst ... etc.
There was no way to tell that from the data I posted, so my apologies.
fyi, once I added that fix, I changed the the dataType param back to 'datatype' and it still worked fine.

Adding StateCode dash StateName to the autocomplete using MVC4.5 and a JsonResult

I am trying to get the state code to be followed by a dash and the state name using an ajax autocomplete syntax. I'm using jQuery and jQueryUI and the jQueryUI autocomplete function to attempt this.
I am using this json result:
[{"code":"AK","name":"Alaska"},{"code":"AL","name":"Alabama"},
{"code":"AR","name":"Arkansas"},{"code":"AZ","name":"Arizona"},
{"code":"CA","name":"California"}, ... ]
And I'm using this jQuery ajax call with an embedded
$.ajax({
url: '/Cats/State/List',
type: 'POST',
dataType: 'json',
success: function (data) {
$('#Cat_stateCode').autocomplete(
{
source: data.code + '-' + data.name,
minLength: 2
});
}
});
The mvc controller JSON Result looks like this:
public JsonResult List()
{
return Json(db.States.ToList(), JsonRequestBehavior.AllowGet);
}
How do I get the auto complete to show:
CA - California
CO - Colarado
If I type out C? Or does Autocomplete only work with simple json like {"AK", "AL", "AR" ... }?
Figured it out:
$("#Cat_stateCode").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Cat/States/List",
dataType: "json",
data: {
style: "full",
maxRows: 12,
req_state_part: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.code + ' - ' + item.name,
value: item.code
}
}));
// alert("data.code:" + data);
},
error: function (e) {
alert("e.error:" + e.error);
}
});
},
minLength: 1,
select: function (event, ui) {
//alert("ui item:" + ui.item ? "Selected: " + ui.item.label : "Nothing selected, input was " + this.value); //todo: remove after dev
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
In my mvc CatStateController I have this:
public JsonResult List(String stateAbbreviation)
{
String StateNameORStateCodeContains = Request.Params["req_state_part"];
return Json(db.States.Where(state => state.name.Contains(StateNameORStateCodeContains) || state.code.Contains(StateNameORStateCodeContains)).ToList(), JsonRequestBehavior.AllowGet);
}
So it looks like it doesn't sent the term over, it only send over some params you make up in the data element. Since you can make up pretty much anything its up to the developers imagination. One thing I was trying to do was create a closure b/c I have a lot of different animals with different states. And I need to create this same autocomplete function for each of them. So I need to ask another question how do you remove the auto complete so I can call that same function from many different ids, or do I just separate them out with a comma like so:
$("#Cat_stateCode,#Dog_stateCode,#Penguin_stateCode...").autocomplete({ ... ???
And I believe the answer to the second part is in here. I think its insinuating just add some class or attribute to the applicable input tags and then just perform an each over them and them lastly apply the autocomplete to the $(this).autocomplete immediately after each each iteration occurs.
Found a better way with just set the input tag to have a class="cssClassName". Had to use the TextBoxFor:
#Html.TextBoxFor(model => model.Cat.stateCode, new { #class = "StateCodeAutoComplete" })

Retrieving search data from database using jQuery autocomplete?

I am using jQuery UI Autocomplete plugin for better data input in my ASP.NET web application.
http://jqueryui.com/demos/autocomplete/
However, I think I have somehow lost in this plugin.
I would like to ask what I should do in order to use this autocomplete function with the data retrieve from database?
I expect Ajax should be used for the real-time search,
but I have no idea how it can be done after looking at the demo in the website above.
Thanks so much.
Update:
Here is the code I have tried, doesn't work, but no error in firebug too.
$('#FirstName').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Contact/FirstNameLookup?firstName=",
type: "POST",
data: {
"firstName": $('#FirstName').val()
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.FirstName,
value: item.FistName
}
}));
}
});
}
});
You need to create an action that does the lookup and returns the result as a JsonResult
e.g.
public ActionResult FirstNameLookup(string firstName)
{
var contacts = FindContacts(firstname);
return Json(contacts.ToArray(), JsonRequestBehavior.AllowGet);
}
I'm not sure if this will solve all your problems but here are a couple of edits you can make.
you don't need the "?firstname=" part of the url since you are using the data parameter for you ajax request.
rather than grabbing your search term with $('#FirstName').val(), try using the term property of the request object (request.term).
for example:
$('#FirstName').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Contact/FirstNameLookup",
type: "POST",
data: {
"firstName": request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.FirstName,
value: item.FistName
}
}));
}
});
}
});

Jquery Autocomplete with json and using parameters

I am trying to do an autocomplete input field. Everytime a user type a letter in that field, the value of the field is sent to the server and the server answer with words that match.
var acOptions = {
source:function (request, response) {
$.ajax({
url: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw",
type: "GET", dataType: "json",
data: { expr: request.term},
success: function (data) {
response($.map(data, function (item) {
return item.value;
}))
}
})
},
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
This is an example of data from the server:
[{"value":"Greater"},{"value":"great"},{"value":"greatly"},{"value":"Greater-Axe"}]
The previous code do the right request to the server (and the server answer right) but it does not display anything in the text field.
I tried to do the autocomplete without an explicit ajax object but then I couldn't send the current value of the field (parameter "expr" of the request) to the server:
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=",
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
Thank you for your help!
You can use jQuery to pull the value of your field to add it to URL parameter string.
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=" + $('#ID_OF_YOUR_TEXTBOX').val(),
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);

jQuery UI - Autocomplete with extra params - returned data

All,
I've moved on to using the ui autocomplete rather than the plugin, took me a while to figure out extra params based on an example I found here, but that part works.
I'm having problems with dealing with the return data. In the code below I can alert out the title being returned, but I get a drop down of 'UNDEFINED' in the browser.
Thanks in advance.
$('#DocTitle').autocomplete({
source: function(request, response) {
$.ajax({
url: "index.pl",
dataType: "json",
data: {
Title: request.term,
maxRows: 10
},
success: function(data) {
response($.map(data, function(item) {
alert(item.TITLE);
return {
TITLE: item.TITLE
}
}))
}
})
}
});
I am using jquery UI autocomplete as follows and it is working quite fine for me. You may try on the similar lines.
$('input[type=text][name=City]').autocomplete({
source: function(request, response) {
$.getJSON($('input#CitySuggestionsLink').val(), {
term: request.term,
stateId: $('select#StateName option:selected').attr('value')
}, response);
},
search: function() {
// custom minLength
var term = this.value;
if (term.length < 1) {
return false;
}
},
delay: 200,
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
return false;
}
});