jquery smartAutocomplete with infinite scroll - jquery-ui

how we can have autocomplete combo with infinit scroll?
i found an autocomplete jquery ui with infinit scroll, but this autocomplete gets data by pagemethods. but i want to use it in mvc application and want to use an action of a controller to retrieving data.
to use this autocomplete by pagemethods should do this:
$(document).ready(function () {
//Input for testing purposes
$("#inp").smartautocomplete({
getDataFunc: getData,
pageSize: 15,
autoFocus: true
});
});
//Function the SA plugin called when data is needed.
var getData = function (input, pageIndex, pageSize, callback) {
PageMethods.GetData(input, pageIndex, pageSize, function (response) {
if (response) {
response = $.map(response, function (item) {
return {
label: item,
value: item
}
});
callback(response);
}
else callback();
});
};
but i change the way of getting data by using $.ajax:
var getData = function (input, pageIndex, pageSize, callback) {
$.getJSON(
{ url: '#Url.Action("GetData", "Home")' },
{ input: input, pageIndex: pageIndex, pageSize: pageSize },
function (response) {
if (response) {
response = $.map(response, function (item) {
return {
label: item,
value: item
};
});
callback(response);
}
else callback();
});
};
but it does not work, and the action does not called.
this autocomplete is accessible here:
http://www.codeproject.com/Articles/325719/JQueryUI-smartAutocomplete?fid=1683905
i want to know if there is any other solution to have autocomplete with infinit scroll

Replace PageMethod call with AJAX call
$.ajax({
url: '#Url.Action("GetData", "Default")',
type: 'GET',
dataType: 'json',
data: {
input: input,
pageIndex: pageIndex,
pageSize: pageSize
},
success: function (response) {
//alert(response);
if (response) {
response = $.map(response, function (item) {
return { label: item, value: item };
});
callback(response);
} else {
callback();
}
},
error: function (e) {
alert('error' + e);
},
contentType: 'application/json; charset=utf-8'
});
Make sure your controller action is returning JSONResult
return new JsonResult {JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = data };//new {result = data}
Hope this helps.

Related

Autocomplete results will not be displayed inside asp.net mvc partial view

I have the following script that is rendered inside my _layout view:-
$(document).ready(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
and i added the following field to apply autocomplete on it:-
<input name="term" type="text" data-val="true"
data-val-required= "Please enter a value."
data-autocomplete-source= "#Url.Action("AutoComplete", "Staff")" />
now if i render the view as partial view then the script will not fire, and no autocomplete will be performed, so i added the autocomplete inside ajax-success as follow:-
$(document).ready(function () {
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
});
now after adding the AjaxSuccess the action method will be called, and when i check the response on IE F12 developers tools i can see that the browser will receive the json responce but nothing will be displayed inside the field (i mean the autocomplete results will not show on the partial view)?
EDIT
The action method which is responsible for the autocomplete is:-
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term).Select(a => new { label = a.SamAccUserName }).ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
EDIT2
here is the script which is responsible to show the modal popup:-
$(document).ready(function () {
$(function () {
$.ajaxSetup({ cache: false });
//$("a[data-modal]").on("click", function (e) {
$(document).on('click', 'a[data-modal]', function (e){
$('#myModalContent').css({ "max-height": screen.height * .82, "overflow-y": "auto" }).load(this.href, function () {
$('#myModal').modal({
//height: 1000,
//width: 1200,
//resizable: true,
keyboard: true
}, 'show');
$('#myModalContent').removeData("validator");
$('#myModalContent').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#myModalContent');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", "disabled");
$('#progress').show();
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.ISsuccess) {
$('#myModal').modal('hide');
$('#progress').hide();
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
location.reload();
// alert('www');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
bindForm();
}
}
});
}
else {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
$('#progress').hide();
return false;
}
return false;
});
}
});
First, you don't need to wrap you ajaxSuccess fucntion in ready function.
Second, it's better to use POST when you get Json from server.
I tried to seproduce your problem, but have no luck.
Here how it works in my case(IE 11, MVC 4)
script on _Layout:
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: function (request, response) {
$.post(target.attr("data-autocomplete-source"), request, response);
},
minLength: 1,
delay: 1000
});
});
});
Controller method:
[HttpPost]
public JsonResult AutoComplete()
{
return Json(new List<string>()
{
"1",
"2",
"3"
});
}
Partial View html:
<input name="term" type="text" data-val="true"
data-val-required="Please enter a value."
data-autocomplete-source="#Url.Action("AutoComplete", "Stuff")" />
UPDATE:
I find out what your problem is. Jquery autocomplete needs array of objects that have lable and value properties. So if you change your controller code like this and it will work.
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term)
.Select(a => new { label = a.SamAccUserName, value = a.SamAccUserName })
.ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
Also you can do it on client side with $.map jquery function you can see example here

Jquery Autocomplete in mvc if user types text which is not in autocomplete list

Jquery Autocomplete UI in mvc .. If user enter some text which is not in list it should alert not in list ....
In View:-
$("#loc").autocomplete({
source: function (request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
if (data.length == 0) {
alert('Please select an item from the list');
document.getElementById('Loc').value = "";
document.getElementById('Loc').focus();
document.getElementById('Loc').style.border = "solid 1px red";
}
else
response($.map(data, function (item) {
document.getElementById('Location').style.border = "solid 1px black";
return { label: item.Name, value: item.Name, id: item.LocationId };
}));
}
})
},
select: function (event, ui) {
$("#locationID").val(ui.item.id);
}
});
in Controller:
public JsonResult AutoLoc(string term)
{
var result = (from r in db.S
where r.Name.ToLower().Contains(term.ToLower())
select new { r.Name, r.id }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
Here suppose we enter 'a' then it will not alert any message . Though 'a' is not in list
when we enter any character which is not in autocomplete list it should alert and make that box as red.
Actually What is happening in 'data' we are getting values because in controller we are writing a query as contains or startwith 'a' so value is returned but as a individual 'a' is not in list that starts with or contains 'a'.
Try this:
$("#loc").autocomplete({
source: function(request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
var found = $.map(data, function(item) {
return {label: item.Name, value: item.Name, id: item.LocationId};
});
if (found.length === 0) {
alert('Please select an item from the list');
$("#loc").val("");
$('#loc').focus();
$('#loc').css("border", "solid 1px red");
} else {
$('#loc').css("border", "none");
}
response(found);
}
});
},
select: function(event, ui) {
$("#locationID").val(ui.item.id);
}
});
In View:
$("#loc").autocomplete({
source: function (request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
var found = $.map(data, function(item) {
return {label: item.Name, value: item.Name, id: item.LocationId};
});
}
});
},
change: function (event, ui) {
var referenceValue = $(this).val();
var matches = false;
$(".ui-autocomplete li").each(function () {
if ($(this).text() == referenceValue) {
matches = true;
return false;
}
});
if (!matches) {
alert('Please select an item from the list');
this.value = "";
this.focus();
this.style.border = "solid 1px red";
}
else {
document.getElementById("submitbutton").disabled = false;
this.style.border = "solid 1px black";
}
}
});
Now when we type 'a' it will alert and show the box border in red color......
This is what i wanted....

get instance of map in jquery ui map

i want to make the markers clustered with markerClusterer but i cannot get the map instance with jquery ui map . js
tried:
var map = $('#map_canvas').gmap('getMap');
or
var map = $('map_canvas').gmap('get', 'map');
and after:
var markerCluster = new MarkerClusterer(map, allMarkers);
but with errors
Thank you
Tried this . No Errors but no clusters...
$('#map_canvas').gmap({ 'callback': function () {
var self = this;
$.getJSON('Data/markers.json', function (data) {
$.each(data.markers, function (i, marker) {
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude,marker.longitude)}).click(function () {
$.ajax({
type: "GET",
url: "/LocoMap/LocoMap/InfoMobilePartialView/",
data: { latitude: marker.latitude, longitude: marker.longitude},
success: function (data) {
$("#marker-info").remove();
$(document.body).append("<div id='marker-info' data-role ='page'> </div>");
var $contentDiv = $("#marker-info");
$contentDiv.html(data).trigger('create');
$.mobile.changePage("#marker-info", { changeHash: false, type: "get", transition: 'pop',rel:"external" });
},
error: function (errorData) { onError(errorData); }
});
});
});
});
self.set('MarkerClusterer', new MarkerClusterer(this.get('map'), this.get('markers')));
}});
$('#map_canvas').gmap({'zoom': 2, 'disableDefaultUI':true}).bind('init', function(evt, map) {
$.getJSON( 'Data/markers.json', function(data) {
$.each( data.markers, function(i, m)
$('#map_canvas').gmap('addMarker', { 'position': new google.maps.LatLng(m.latitude, m.longitude), 'bounds':true } );
});
});
$('#map_canvas').gmap('set', 'MarkerClusterer', new MarkerClusterer(map,$(this).gmap('get', 'markers')));
});
with no errors and no clusters
it seems **$(this).gmap('get', 'markers')));** returns Array[0]

select event not working

I try to store an identifier into an hiddenfield when a value is selected with a jquery autocomplete field.
But the select event is never fired and I dont't see why..
here is my code
$(document).ready(function () {
$('#test').autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Controller/Method", type: "POST", dataType: "json",
data: { Comparaison: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.text, value: item.text, id : item.value };
}));
},
select: function (event, ui) {
alert("selected");
//$("#idProprio").val(ui.item.id);
}
});
},
});
});
The autocompletion is properly working, I can see the values, select one but when I select a value nothig happens..
I believe your curly braces are wrong. select is being set as part of the ajax parameter, not autocomplete:
$(document).ready(function () {
$('#test').autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Controller/Method", type: "POST", dataType: "json",
data: { Comparaison: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.text, value: item.text, id : item.value };
}));
}
});
},
select: function (event, ui) {
alert("selected");
//$("#idProprio").val(ui.item.id);
}
});
});

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
});

Resources