Jquery Autocomplete not populating after error thrown - javascript

I am running a ASP.Net MVC application and using jQuery's Autocomplete in one of the textboxes to populate contract numbers after the 6th digit/character.
It is working flawlessly, until after an error is thrown for a validation check.
My code :
$(document).ready(function () {
$("#ContractNumber").autocomplete({
source: '#Url.Action("GetContractId")',
open: function () { $('ul.ui-autocomplete').hide().fadeIn() },
close: function () { $('ul.ui-autocomplete').show().fadeOut() },
minLength:6
});
});
The code that redirects to the correct controller to get the contract number is here:
$(document).ready(function () {
//$('body').on('focus', "#ContractNumber", function () {
$("#ContractNumber").autocomplete({
source: function (request, response) {
$.ajax({
url: "/PurchaseRequestDetail/GetContractId",
minLength: 1,
data: { Prefix: request.term },
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };;
}))
}
})
}
});
Here is the autocomplete that is working fine, before the error:
I wanted this autocomplete to work, on focus of the textbox, whether a validation error thrown or not.
validation error:
The code that checks for ModelState if contract number is not found :
if (contractNo is null)
{
// row.ContractId = foundList.ContractId;
db.PurchaseRequestDetail.Add(newRow);
db.SaveChanges();
}
else if (contractNo != null)
{
if (foundList is null)
{
ModelState.AddModelError("ContractNumber", "Contract Number not in the database.");
// reload the drop down lists, they don't survive the trip to the server and back
viewModel.ContractList = GetContractList(viewModel.ContractId);
return View("CreateEdit", viewModel);
}
}
Any pointers in correcting this would be helpful.
TIA.

Related

Error: object doesn't support 'autocomplete'

I have this function using the jquery autocomplete widget, that I am getting the following error:0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'autocomplete'
On my html page, in the head section I have included the following tags.
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery-ui-1.11.4.min.js"></script>
The function is called by a variety of option button calls to do several different query's. I have this function in a different application that works well but here it is not.
function AutoComplete(Type) {
//create AutoComplete UI component
$("#txtCriteria").autocomplete({
source: function (request, response) {
$.ajax({
autoFocus: true,
async: false,
delay: 250,
url: "wsReports.asmx/AutoComplete",
data: "{'Type':'" + Type + "', 'filter':'" + request.term + "'}",
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 {
label: item.ACName,
value: item.ACCode
} // end of return
})) // end of response
} // end of success
}); // end of ajax
}, // end of source
select: function (event, ui) {
if (ui.item.value == "") {
alert("nothing to select");
}
else {
// prevent autocomplete from updating the textbox
event.preventDefault();
// manually update the textbox and hidden field
$(this).val(ui.item.label);
}
}, // end of select
change: function (event, ui) {
if (!ui.item) {
$(event.target).val('');
}
},
}) // end of txtCriteria.autocomplete
} // end of AutoComplete
Any ideas why it is not recognized in the above situation?
My fault. The jquery.js and bootstrap were loading after the jquery-ui.

Reinitialze onChange event for Bootstrap multiselect

I have a series of multiselect dropdown controls. The first one (users) causes the second one (userGroups) to update when one of its values is changed and the second one (userGroups) causes the third one (theaters) to update the contents of its list.
The onChange event for the first dropdown (users) is working fine. But, the second one (userGroups) onChange event is not firing when one of it's values is changed and thereby not updating the list of the third dropdown (theaters).
I know from having worked with Javascript, the onChange needs to be reinitiazed; but, I do not know how to do this with the Bootstrap multiselect. My code follows:
$('.users').multiselect({
numberDisplayed: 1,
maxHeight: 400,
includeSelectAllOption: false,
enableCaseInsensitiveFiltering: true,
filterBehavior: 'both',
disableIfEmpty: true,
onChange: function (element, checked) {
var userName = $('.users').val();
if (userName != null) {
userName = userName.toString();
}
$.ajax({
url: '#Url.Action("LoadUserGroups")',
data: { "userName": userName },
success: function (data) {
$('.userGroups').multiselect('destroy');
$('.userGroups').replaceWith($(data));
$('.userGroups').multiselect('rebuild');
},
error: function (xhr) {
$('.userGroups').multiselect('destroy');
$('.userGroups').multiselect('rebuild');
}
});
}
});
$('.userGroups').multiselect({
numberDisplayed: 1,
maxHeight: 400,
includeSelectAllOption: false,
enableCaseInsensitiveFiltering: true,
filterBehavior: 'both',
disableIfEmpty: true,
onChange: function (element, checked) {
javascript: console.log("OnChange event fired");
var groupId = $('.userGroups').val();
if (groupId != null) {
groupId = groupId.toString();
}
$.ajax({
url: '#Url.Action("LoadTheaters")',
data: { "groupId": groupId },
success: function (data) {
$('.theaters').multiselect('destroy');
$('.theaters').replaceWith($(data));
$('.theaters').multiselect('rebuild');
},
error: function (xhr) {
$('.theaters').multiselect('destroy');
$('.theaters').multiselect('rebuild');
}
});
}
});
});
If anyone can show me how to do this or at least point me in the right direction, I would much appreciate it. Thanks in advance.
Ok -- I got it to work. Here is what I was doing before:
$.ajax({
url: '#Url.Action("LoadUserGroups")',
data: { "userName": userName },
success: function (data) {
$('.userGroups').multiselect('destroy');
$('.userGroups').replaceWith($(data));
$('.userGroups').multiselect('rebuild');
},
error: function (xhr) {
$('.userGroups').multiselect('destroy');
$('.userGroups').multiselect('rebuild');
}
});
I made the following changes that maintained the userGroups dropdown so the onChange event would fire:
$.ajax({
url: '#Url.Action("LoadUserGroups")',
data: { "userName": userName },
success: function (data) {
$('.userGroups').empty();
$('.userGroups').append($(data).find('option'));
$('.userGroups').multiselect('rebuild');
},
error: function (xhr) {
$('.userGroups').empty();
$('.userGroups').multiselect('rebuild');
}
});
Works like it should now.

show a dialog box , when hovering over the auto complete records

I have the following JavaScript code to do an autocomplete:
$("#Technology2_Tag").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Content("~/Switch/AutoComplete2")",
dataType: "json",
minLength: 2, delay: 2000,
data: {
term: request.term,
SearchBy: $("#ChoiceTag").prop("checked") ? $("#ChoiceTag").val() : $("#ChoiceName").val(),
},
success: function (data) {
response(data);
}
});
},
});
And I am returning the autocomplete records as JSON:
public ActionResult AutoComplete2(string term, string SearchBy)
{
if (SearchBy == "Tag")
{
var tech = repository.AllFindTechnolog(term).OrderBy(p => p.Tag).Select(a => new { label = a.Tag }).ToList();
return Json(tech, JsonRequestBehavior.AllowGet);
}
else
{
var tech = repository.FindActiveResourceByName(term, true).OrderBy(p => p.RESOURCENAME).Select(a => new { label = a.RESOURCENAME }).ToList();
return Json(tech, JsonRequestBehavior.AllowGet);
}
}
But my question is how I can show a dialog the contains additional info about the record, when the user hovers over an autocomplete record.
what i am thinking of is as follows:
when the user hovers over any autocomplete record, to fire a JavaScript function.
the function calls an action method, that returns JSON.
to build the dialog box using the returned JSON object.
First you need to create a div let's say with the id=mydiv which can be a dialog. Initialize it as a dialog.
Then in your autocomplete use focus event. Which will handle an Ajax function which will call an Action (this action can return a Partial view) and will fill your div with the description.
$("#mydiv").dialog();
$ ("#Technology2_Tag").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Content("~/Switch/AutoComplete2")",
dataType: "json",
minLength: 2, delay: 2000,
data: {
term: request.term,
SearchBy: $("#ChoiceTag").prop("checked") ? $("#ChoiceTag").val() : $("#ChoiceName").val(),
},
success: function (data) {
response(data);
}
});
},
focus: function(event,ui){
var element =ui.item.val;
$.ajax({
url: "#Url.Content("~/Switch/ActionDescription")",
dataType: "json",
data: {
hoverelment: element },
success: function (data) {
$('#myDiv').append(data);
$('#myDiv').show();
}
});
}
});
I gave you lines, you have to create another action which will receive a parameter, can send a partial view or just string.
public ActionResult ActionDescription(string hoverlement)
{
.........//linq queries to retrieve description by hoverelement
}
I hope it will help.

Alter the filter on autocomplete to allow sorting on complete string

I have a functioning autocomplete jQuery input control but there are two things it is doing that I would like to alter.
First, it fires again and again. I would like for the data to be returned once, cached and not called again.
Second, I would like for the user to type in the control and based on what they type be able to search the entire string and not just the beginning.
This is my functioning script that returns data to the autocomplete and WORKS.
<script type="text/javascript">
$(function () {
$('#datePicker').datepicker();
});
$(document).ready(function() {
$("#autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "FacilitiesAsync",
type: 'GET',
cache: true,
data: 'sourceDb=myDb',
dataType: 'json',
success: function (json) {
// call autocomplete callback method with results
response($.map(json, function (name) {
return {
label: name.label,
value: name.value
};
}));
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
$("#autocomplete").text(textStatus + ', ' + errorThrown);
}
});
},
select: function (event, ui) {
$('#autocomplete').val(ui.item.label);
return false;
},
messages: {
noResults: '',
results: function () {
}
}
});
});
</script>
I found this bit of code that overrides the filter feature of the autocomplete but I have NO IDEA where to add this. I have tried several places to no avail....
// Overrides the default autocomplete filter function to search only from the beginning of the string
$("#autocomplete").autocomplete.filter = function (array, term) {
var matcher = new RegExp("\\b" + $.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
My input control looks like this.
<input id="autocomplete" />
I appreciate the direction...
To cache the data from your server, setup a separate function which handles (and caches, if necessary) the response from your ajax call:
var cachedResult = null;
function fetchResponse(callback) {
if (cachedResult) callback(cachedResult)
$.ajax({
url: "FacilitiesAsync",
type: 'GET',
cache: true,
data: 'sourceDb=myDb',
dataType: 'json',
success: function (json) {
// call autocomplete callback method with results
var cachedResult = $.map(json, function (name) {
return {
label: name.label,
value: name.value
};
});
callback(cachedResult);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
$("#autocomplete").text(textStatus + ', ' + errorThrown);
}
});
}
$(document).ready(function() {
$("#autocomplete").autocomplete({
source: function (request, response) {
fetchResponse(function(result) {
response(result)
})
}
});
});
As for the custom matcher, look no further than the docs, in the Using a custom source callback to match only the beginning of terms example. Your custom matcher only differs in the regex pattern. Note also that this is all done within the "source" callback.

Jediitable, autocomplete and autogrow jquery not working

I am trying to use autocomplete and autogrow with the Jeditable jquery plugin and cannot seem to incorporate both. I currently have the Jeditable + autocomplete working perfectly. When I tr to add code for the autogrow it doesn't work and causes a post back when I hit the save button. Any help would be appreciated.
This is what I have so far:
$('#directionList').autocomplete({
source: function (request, response) {
$.ajax({
url: '../api/standarddirections/?q=' + request.term,
dataFilter: function (data) { return data; },
success: response
});
},
minLength: 2
});
$.editable.addInputType('autocomplete', {
element: $.editable.types.textarea.element,
plugin: function (settings, original) {
$('textarea', this).autocomplete(settings.autocomplete);
}
});
$(".directionAutoComplete").editable(function (value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return (value);
}, {
type: "autocomplete",
indicator: 'Saving...',
tooltip: "Enter a direction...",
onblur: function (value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return (value);
},
cancel: 'Cancel',
submit: 'Save',
autocomplete: {
source: function (request, response) {
$.ajax({
url: '../api/standarddirections/?q=' + request.term,
dataFilter: function (data) { return data; },
success: response
});
},
minLength: 2
}
});
Here's some reference material:
Jeditable
Jeditable - Auto Grow Tutorial
For those running into this problem I have gotten it to work. I went with the growfield plugin just because the autogrow one was having some weird results (it worked, but the formatting looked off when I saved it so I just opted to go the easier route of using a different plugin.)
Here's my final code:
$.editable.addInputType('growfield', {
element: function (settings, original) {
var textarea = $('<textarea>');
if (settings.rows) {
textarea.attr('rows', settings.rows);
} else {
textarea.height(settings.height);
}
if (settings.cols) {
textarea.attr('cols', settings.cols);
} else {
textarea.width(settings.width);
}
// will execute when textarea is rendered
textarea.ready(function () {
// implement your scroll pane code here
});
$(this).append(textarea);
return (textarea);
},
plugin: function (settings, original) {
// applies the growfield effect to the in-place edit field
$('textarea', this).growfield(settings.growfield);
$('textarea', this).autocomplete(settings.autocomplete);
}
});
$(".directionAutoComplete").editable(function (value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return (value);
}, {
type: "growfield",
indicator: 'Saving...',
tooltip: "Enter a direction...",
onblur: function (value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return (value);
},
cancel: 'Cancel',
submit: 'Save',
growfield: {},
autocomplete: {
source: function (request, response) {
$.ajax({
url: '../api/standarddirections/?q=' + request.term,
dataFilter: function (data) { return data; },
success: response
});
},
minLength: 2
}
});

Categories

Resources