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

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....

Related

jquery UI Autocomplete with stored list

Hi I'm using jQuery UI Autocomplete and want do something like this: I want to get the list with AJAX when length=3 and this work great it populate the drop-down. Next I want when the length is >3 to use the returned list from the AJAX and filter it. But it give the same list not filtered.
$( ".selector" ).autocomplete({
source:function(request, response) {
var str_req = request.term;
if(str_req.length==3) {
$.ajax({
url: "/?search=1",
type: "GET",
dataType: "json",
data: {term: request.term},
success: function (data) {
auto_data=data;
response(data);
}
});
} else{
return response(auto_data);
}
},
minLength: 3,
select: function( event, ui ) {
console.log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
I would simply set the min to 1 and do a comparison in the source.
$(".selector").autocomplete({
source:function(request, response) {
var str_req = request.term;
if(str_req.length < 3) {
// Send your list back, if it was stored in 'myData'
response(myData);
} elseif(str_req.length==3) {
$.ajax({
url: "/?search=1",
type: "GET",
dataType: "json",
data: {term: str_req},
success: function (data) {
auto_data=data;
response(data);
}
});
} else{
response(auto_data);
}
}
},
minLength: 1,
select: function(event, ui) {
console.log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
You could also do this as a Switch statement:
var str_req = request.term;
switch(true){
case str_req.length < 3:
// Send your list
break;
case str_req.length == 3:
// Perform AJAX & return results
break;
default:
// All other options
response(auto_data);
}

JQuery Autocomplete acts wierd once i publish my website

I am using this functionality to fill the JQuery UI with minimum length set to 2. This code works good when I try to select the list through mouse or through keyboard.
But once I publish my code through my virtual machine it does not work. Neither the minimum length works nor the mouse or keyboard selection works.
Please help me here.
function SPAutoComplete(request, response) {
//debugger;
$.ajax({
url: 'Contracts/SearchSpByNumber',
type: 'GET',
cache: false,
contentType: "application/json; charset=utf-8",
data: request,
dataType: 'json',
success: function (json) {
var i = 0;
i++;
// call autocomplete callback method with results
response($.map(json, function (item) {
return {
label: item.SP_NBR,
SPDesc: item.SP_DESC,
ID: item.ElementID
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('error - ' + textStatus);
console.log('error', textStatus, errorThrown);
}
});
}
$("#SP1").autocomplete({
source: SPAutoComplete,
minLength: 2,
select: function (event, ui) {
// alert('you have selected ' + ui.item.name + ' ID: ' + ui.item.name);
$("#SP1").val(ui.item.label);
$("#SPDesc1").val(ui.item.SPDesc);
$("#SPDesc1").attr("readonly", true);
$("#SP1ID").val(ui.item.ID);
_newDirty = true;
event.preventDefault();
return false;
},
change: function (event, ui) {
debugger;
if (ui.item != undefined || ui.item != null) {
$("#SP1").val(ui.item.label);
$("#SPDesc1").val(ui.item.SPDesc);
$("#SPDesc1").attr("readonly", true);
$("#SP1ID").val(ui.item.ID);
event.preventDefault();
return false;
}
},
focus: function (event, ui) {
debugger;
$("#SP1").val(ui.item.value);
return false;
}
});

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 smartAutocomplete with infinite scroll

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.

Resources