jQuery UI autocomplete (combobox): how to fill it with the result of an AJAX request? - jquery-ui

Is it possible to work with combobox as with usual jquery-ui ajax autocomplete field?
What I need?
I want there will be some default options and when user try to put any letters it must connect to the server to find requested information (as usual remote json autocomplete).
Is it possible at all?

Here's a heavily modified version of the jQueryUI example (gist):
$.widget("ui.combobox", {
_create: function() {
var _self = this
, options = $.extend({}, this.options, {
minLength: 0,
source: function(request, response) {
if (!request.term.length) {
response(_self.options.initialValues);
} else {
if (typeof _self.options.source === "function") {
_self.options.source(request, response);
} else if (typeof _self.options.source === "string") {
$.ajax({
url: _self.options.source,
data: request,
dataType: "json",
success: function(data, status) {
response(data);
},
error: function() {
response([]);
}
});
}
}
}
});
this.element.autocomplete(options);
this.button = $("<button type='button'> </button>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.insertAfter(this.element)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function() {
if (_self.element.autocomplete("widget").is(":visible")) {
_self.element.autocomplete("close");
return;
}
_self.element.autocomplete("search", "");
_self.element.focus();
});
}
});
Usage:
$("input_element_selector").combobox({
initialValues: ['array', 'of', 'values'],
source: /* <-- function or string performing remote search */,
/* any other valid autocomplete options */
});
Example: http://jsfiddle.net/Jpqa8/
The widget uses the supplied initialValues array as the source when the length of the search is "0" (this happens when the user clicks the dropdown button).
Supply a source parameter (function or string) that performs the remote search. You can also use any other options you would usually use with the autocomplete widget.

Related

jquery event.preventDefault() issues with IE 8

In my jquery autocomplete select function, I need to use the event.preventDefault() method to prevent the default ui.item.value from populating the input text box the autocomplete is wired too. This works great in Chrome, however in IE 8 (which is in use by a majority of our users) the .preventDefault() line throws the following error:
Unexpected call to method or property access
Here is the jQuery for good measure. Does anyone know of a work-around for this method in IE 8?
var tempResults = [];
$(function () {
$('#DRMCompanyName').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("compSearchByName", "AgentTransmission")',
type: 'GET',
dataType: 'json',
data: request,
success: function (data) {
tempResults = data;
response($.map(data, function (value, key) {
return {
label: value + " " + key,
value: key
};
}));
},
});
},
minLength: 2,
select: function (event, ui) {
event.preventDefault(); // <-Causing a problem in IE 8...
$('#DRMCompanyName').val(tempResults[ui.item.value]);
$('#DRMCompanyName').text(tempResults[ui.item.value]);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(ui.item.value);
$('#DRMCompanyId').text(ui.item.value);
}
}
});
});
You could use return false instead but as i said in comment: return false = event.preventDefault() + event.stopPropagation() But in your case, should fit your needs.

From Jquery-ui autocomplete to typeahead.js

I am migrating my app to twitter-bootstrap and i would like to replace my jquery-ui autocomplete with typeahead.js.
It would be better to use the feature embedded in twitter-bootstrap but i am ok with the extra typeahead plugin if necessary.
My problem is that i have trouble reproducing the current behaviour especially with the absence of results.
How would you do something like that?
$("#search").autocomplete({
source : myUrl,
delay : 100,
minLength : 2,
select : function(event, ui) {
// do whatever i want with the selected item
},
response : function(event, ui) {
if (ui.content.length === 0) {
ui.content.push({
label : "No result",
value : customValue
});
}
}
});
Basically, if there is no result, i want to display a custom message in the component.
Thanks!
The migration to Bootstrap typeahead would look something like..
$('.typeahead').typeahead({
minLength:2,
updater: function (item) {
/* do whatever you want with the selected item */
},
source: function (typeahead, query) {
/* put your ajax call here..
return $.get('/typeahead', { query: query }, function (data) {
return typeahead.process(data);
});
*/
}
});
EDIT:
I've updated the demo to include a sorter and highlighter. I think this will get you the results you want..
sorter: function(items) {
if (items.length == 0) {
var noResult = new Object();
items.push(noResult);
}
return items;
},
highlighter: function(item) {
if (dataSource.indexOf(item) == -1) {
return "<span>No Match Found.</span>";
}
else {
return "<span>"+item+"</span>";
}
},
Bootstrap Typeahead Demo
I don't think the typeahead has an equivalent to delay, but there are some jquery workarounds for this.
With the latest version of Typeahead.js (0.10) it is now possible to specify an empty template to display when no results are found.
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 2
},{
name: 'examples',
source: examples.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'unable to find any results that match the current query',
'</div>'
].join('\n')
}
});

Asp.net Mvc jquery ajax?

I have links like following.
Deneme Müşteri 2
Deneme Müşteri 2
I want to use jquery ajax post like this:
$(".customer_details").click(function () {
$.ajax({
url: $(this).attr("href"),
type: 'POST',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
});
Or this:
$(".customer_details").click(function () {
$("#customer_operations_container").load($(this).attr("href"));
});
And Action Method
public ActionResult _EditCustomer(int CustomerId)
{
// get customer from db by customer id.
return PartialView(customer);
}
But I cant do what I wanted. When I click to link, PartialView does not load. It is opening as a new page without its parent. I tried prevent.Default but result is the same.
How can I load the partialView to into a div?
Note: If I use link like this <a href="#"> it works.
Thanks.
Maybe the problem is with the actionresult, try with Content to see if that changes anything.
public ActionResult _EditCustomer(int CustomerId)
{
// get customer from db by customer id.
return Content(customer.ToString());
}
Try one of these...
$(".customer_details").click(function (e) {
e.preventDefault()
$.ajax({
url: $(this).attr("href"),
//I think you want a GET here? Right?
type: 'GET',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
});
Or
$(".customer_details").click(function (e) {
e.preventDefault();
$("#customer_operations_container").load($(this).attr("href"));
});
Or
$(".customer_details").click(function (e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$("#customer_operations_container").html(data);
});
});
If none of this works, check if there's any js errors
The problem is when you click on the link you already start navigation to it. So just use e.preventDefault() or return false from the click method to prevent the default behavior
$(".customer_details").click(function (e) {
e.preventDefault();
...
}
This should help you out:
$.ajax({
url: $(this).attr("href"),
type: 'POST',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
return false;
The only thing you where missing is the prevention of A tag working. By returning false your custom event is called and the default event is not executed.
Try this
$(function(){
$(".customer_details").click(function (e) {
e.preventDefault();
});
});
Using ready event
Demo: http://jsfiddle.net/hdqDZ/

Jquery Ajax post animation during ajax process?

I do ajax post on my mvc app when dropdown change.
$(function () {
$('#meters').change(function () {
var analizor_id = $(this).val();
if (analizor_id && analizor_id != '') {
$.ajax({
url: '#Url.Action("AnalizorInfoPartial", "Enerji")',
type: 'GET',
cache: false,
data: { analizor_id: analizor_id },
success: function (result) {
$('#TableAnalizorInfo').html(result);
}
});
}
});
});
DropDown
#Html.DropDownList("sno", new SelectList(Model, "sno", "AnalizorAdi"), "-- Analizör Seçiniz --", new { id = "meters" })
Can I show a loading image or anything else during ajax process? (between begin - finish event) and Code example?
EDIT
Can I use like this?
success: function (result) {
$('#TableAnalizorInfo').html(result);
}
begin:function(){
//show image
}
complete:function(){
//hide image
}
Thanks.
Of course, the events you are looking for are beforeSend and complete:
if (analizor_id && analizor_id != '') {
$.ajax({
url: '#Url.Action("AnalizorInfoPartial", "Enerji")',
type: 'GET',
cache: false,
beforeSend: function() {
// Show your spinner
},
complete: function() {
// Hide your spinner
},
data: { analizor_id: analizor_id },
success: function (result) {
$('#TableAnalizorInfo').html(result);
}
});
}
or you could do it globally for all AJAX requests on the page using global AJAX event handlers:
$(document).ajaxSend(function() {
// Show your spinner
}).ajaxComplete(function() {
// Hide your spinner
});

jQuery UI Autocomplete how to implement Must Match in existing setup?

I have the following code and am curious as how to force the input to match the contents of the autocomplete:
$("#foo").autocomplete({
source: function( request, response ) {
$.ajax({
url: "index.pl",
dataType: "json",
data: {
type: 'foo',
term: request.term
},
success: function( data ) {
response( $.map( data.items, function( item ) {
return {
value: item.id
}
}));
}
});
},
minLength: 1
});
Answering this question for the benefit of anyone who stumbles upon this problem in 2013(yeah right!)
$("#my_input").autocomplete({
source: '/get_data/',
change: function(event, ui) {
var source = $(this).val();
var temp = $(".ui-autocomplete li").map(function () { return $(this).text()}).get();
var found = $.inArray(source, temp);
if(found < 0) {
$(this).val(''); //this clears out the field if non-existing value in <select><options> is typed.
}
}
});
Explanation:
The map() method creates a jQuery object populated with whatever is returned from the function (in this case, the text content of each <li> element).
The get() method (when passed no argument) converts that jQuery object into an actual Array.
Here is the original link of where I saw the solution.
I hope this helps. Thanks!

Resources