How to create generic (reusable) JavaScript autocomplete function - javascript

I now have a working JavaScript autocomplete function, thanks to help from many of you. Now I want to make the function reusable. There are three variables that need to be specified for each instance of the function, as shown below. What I don't know how to do is instantiate this function with different values for these three vars.
Here is my HTML field:
<div class="ui-widget">
Text or Value:
<input type="text" id="dotmatch" />
</div>
And here is the JavaScript code which I want to keep in its own .js file:
var matchFieldName = 'dotmatch';
var resultFieldName = 'dotnumber';
var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList";
$(function() {
$('#' + matchFieldName).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
label: item.Label + "(" + item.Value+ ")",
value: item.Value
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
return ui.item.label;
}
});
});

insin was close. The solution I worked out this morning is;
function AutoComplete(matchFieldName, resultFieldName, lookupURL) {
$('#' + matchFieldName).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
value: item.Value,
label: (item.Label == item.Value) ? item.Label : item.Label + "(" + item.Value + ")"
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
}
});
}
On the web page:
<div id="AutoSuggest">
DOT Job Title or Number:
<input type="text" id="dotmatch" style="width:300px;" />
</div>
And on the web page, after the tag:
<script type="text/javascript" src="js/DOTAutocomplete.js"></script>
<script type="text/javascript">
$(function() {
AutoComplete("dotmatch", "dotnumber", "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList");
});
</script>

It looks like you're using jQuery, so you might want to implement it as a plugin.
(function($) {
$.fn.bobsAutocomplete = function(resultFieldName, lookupURL) {
this.autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({prefixText: request.term, count: 20}),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
label: item.Label + "(" + item.Value+ ")",
value: item.Value
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
return ui.item.label;
}
});
return this;
};
})(jQuery);
Usage:
$("#dotmatch").bobsAutocomplete("dotnumber", "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList");

Related

it showing "undefined" in tree view using ASP.NET MVC with javascript

While fetching data from the oracle database it showing "undefined" in Tree View structure using ASP.NET MVC and Gijgo tree view JQuery plug-in, The Tree View control can display a hierarchical (or nested, or recursive) collection of data in a tree of expandable nodes.. How to solve this?.Please, anyone helps me.
I am trying this link
https://www.codeproject.com/Articles/1185174/How-to-create-Dynamic-draggable-and-droppable-Tree
#section Scripts {
#Scripts.Render("~/bundles/Scripts/jqueryval") <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="#Url.Content("~/Scripts/conditional-validation.js")" type="text/javascript"></script>
<script src="~/Scripts/Gijgo/gijgo.js"></script>
<link href="http://code.gijgo.com/1.3.0/css/gijgo.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//'Hierarchy/GetHierarchy'
$(document).ready(function () {
var Usertree = "";
var tree = "";
$.ajax({
type: 'get',
dataType: 'json',
cache: false,
url: '/Hierarchy/GetHierarchy',
success: function (records, textStatus, jqXHR) {
tree = $('#tree').tree({
primaryKey: 'Id',
dataSource: records,
dragAndDrop: true,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
Usertree = $('#Usertree').tree({
primaryKey: 'ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
tree.on('nodeDrop', function (e, ID, PID) {
currentNode = ID ? tree.getDataById(Id) : {};
console.log("current Node = " + currentNode);
parentNode = PID ? tree.getDataById(PID) : {};
console.log("parent Node = " + parentNode);
if (currentNode.PID === null && parentNode.PID === null) {
alert("Parent node is not droppable..!!");
return false;
}
// console.log(parent.HierarchyLevel);
var params = { id: ID, parentId: PID };
$.ajax({
type: "POST",
url: "/Hierarchy/ChangeNodePosition",
data: params,
dataType: "json",
success: function (data) {
$.ajax({
type: "Get",
url: "/Hierarchy/GetHierarchy",
dataType: "json",
success: function (records) {
Usertree.destroy();
Usertree = $('#Usertree').tree({
primaryKey: 'ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
}
});
}
});
});
$('#btnGetValue').click(function (e) {
var result = Usertree.getCheckedNodes();
if (result == "") { alert("Please Select Node..!!") }
else {
alert("Selected Node id is= " + result.join());
}
});
//delete node
$('#btnDeleteNode').click(function (e) {
e.preventDefault();
var result = tree.getCheckedNodes();
if (result != "") {
$.ajax({
type: "POST",
url: "/Hierarchy/DeleteNode",
data: { values: result.toString() },
dataType: "json",
success: function (data) {
alert("Deleted successfully ");
window.location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
},
});
}
else {
alert("Please select Node to delete..!!");
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
// show model popup to add new node in Tree
$('#btnpopoverAddNode').click(function (e) {
e.preventDefault();
$("#modalAddNode").modal("show");
});
//Save data from PopUp
$(document).on("click", "#savenode", function (event) {
event.preventDefault();
$.validator.unobtrusive.parse($('#formaddNode'));
$('#formaddNode').validate();
if ($('#formaddNode').valid()) {
var formdata = $('#formaddNode').serialize();
// alert(formdata);
$.ajax({
type: "POST",
url: "/Hierarchy/AddNewNode",
dataType: "json",
data: formdata,
success: function (response) {
// $("#modalAddNode").modal("hide");
window.location.reload();
},
error: function (response) {
alert('Exception found');
// $("#modalAddNode").modal("hide");
window.location.reload();
},
complete: function () {
// $('.ajax-loader').css("visibility", "hidden");
}
});
}
});
//Close PopUp
$(document).on("click", "#closePopup", function (e) {
e.preventDefault();
$("#modalAddNode").modal("hide");
});
$('.rbtnnodetype').click(function (e) {
if ($(this).val() == "Pn") {
$('.petenddiv').attr("class", "petenddiv hidden");
$("#ParentName").val("");
}
else {
$('.petenddiv').attr("class", "petenddiv");
}
});
});
</script>
}
Just make sure you name the property “text”, including lowercases, as the library binds this field to the label. Not having a property with this name renders it undefined.

how use autocomplete jquery for 3 same class

i used jqueryui autocomplete iwant be the same work for some input text
but when i use $(this).val() for send value of textbox it show error and when i use (".Degree").val() shows and send to server first textbox it incorrect
function DegreeAutoComplete() {
$(".Degree").autocomplete({
position: { my: "right top", at: "right bottom", collision: "none" },
source: function (request, response) {
var spin = $(".spinnerDegree");
spin.addClass("fa-spin fa-spinner");
$.ajax({
url: "#Url.Action("GetDegree")",
type: "POST",
dataType: "json",
data: { search: $(".Degree").val() },
success: function (data) {
spin.removeClass("fa-spin fa-spinner");
response($.map(data, function (item) {
return { label: item.PersianName, value: item.PersianName, id: item.Id };
}));
}
});
},
messages: {
noResults: '',
results: function (resultsCount) { }
},
select: function (event, ui) {
// ui.item.value contains the id of the selected label
alert($(this).val());
$(this).attr("sel", ui.item.id);
}
});
}
when i use: $(this).val();
elem.nodeName is undefined
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[elem.nodeName.toLowerCa...
how can i fix it
this refers to ajax object inside it. Save this reference before using it in inside scope.
var spin = $(".spinnerDegree");
spin.addClass("fa-spin fa-spinner");
var $that = $(this);// save reference
$.ajax({
url: "#Url.Action("
GetDegree ")",
type: "POST",
dataType: "json",
data: { search: $that.val() },//use $that var here
success: function(data) {
spin.removeClass("fa-spin fa-spinner");
response($.map(data, function(item) {
return { label: item.PersianName, value: item.PersianName, id: item.Id };
}));
}
});
EDIT:
Just checked jquery UI doc
You should use request.term thats it.
source: function(request, response) {
$.ajax({
url: "#Url.Action("GetDegree")",
type: "POST",
dataType: "json",
data: {
search: request.term
},
success: function(data) {
//....
}
});
}

jQuery Autocomplete syntax?

I haven't had a lot of experience with jQuery but below is Autocomplete code that is successfully bolding the search characters in the search result dropdown rows:
.autocomplete({
delay: 500,
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
var list = $.ui.autocomplete.filter(availableTags, extractLast(request.term));
if (request.term) {
regex = new RegExp('(' + extractLast(request.term) + ')', 'gi');
list = list.map(function(item) {
return {
label: item.label.replace(regex, '<b>$1</b>'),
value: item.value
}
})
}
response(list);
},
I'm now trying to switch the source to an AJAX lookup. Can anyone let me know what the edit would be to the following AJAX code to get bold text characters like the first code example does?
.autocomplete({
delay: 500,
minLength: 0,
source: function (request, response) {
$.ajax({
url: 'default.aspx/fGetCityLookupData',
data: "{'strSearchText': '" + extractLast(request.term) + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('|')[1],
value: item.split('|')[0]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
TIA
Mark
Answered at another forum here: http://forums.asp.net/p/2092693/6042551.aspx?p=True&t=635965068036236809

my jquery autocomplete not working

i use jquery for create an autocomplete for a textbox, data fetches from an an asmx webservice. i monitor my code on firebug ,this tool shows request sent and xml response recieved . but autocomplete not open for textbox :(
Could someone please tell me why my code for the jquery autocomplete is not working?
jquery code:
<link href="../Script/MainCSS.css" rel="stylesheet" />
<link href="../Script/jquery-ui.css" rel="stylesheet" />
<script src="../Script/jquery-1.10.2.js"></script>
<script src="../Script/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$('.textBox').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Services/BusService.asmx/GetRouteInfo",
data: { param: $('.textBox').val() },
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 {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message)
// console.log("Ajax Error!");
}
});
},
minLength: 2 //This is the Char length of inputTextBox
});
});
</script>
my c# code:
[WebMethod]
public string[] GetRouteInfo(string param)
{
List<string> list_result = new List<string>();
AutoTaxiEntities useEntity = new AutoTaxiEntities();
System.Data.Entity.Core.Objects.ObjectResult<DAL.Model.SP_FIND_ROUTE_ROUTESTOPS_Result> sp_result = useEntity.SP_FIND_ROUTE_ROUTESTOPS(param);
foreach (DAL.Model.SP_FIND_ROUTE_ROUTESTOPS_Result sp_result_item in sp_result.ToList())
{
list_result.Add(sp_result_item.ID + "," + sp_result_item.ITEMTYPE + "," + sp_result_item.TITLE);
}
return list_result.ToArray();
}
Looking at your added script references, i think you have not added autocomplete.js script. Please add it and try it once.Please click here
$(document).ready(function () {
$('#<%=txtSearch.ClientID%>').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: "/Services/BusWebService.asmx/GetRouteInfo",
data: "{ 'param': '" + request.term + "' }",
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
itemid: item.split(',')[0],
itemtype: item.split(',')[1],
label: item.split(',')[2]
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (event, ui) {
$('#<%=hfItem.ClientID%>').val(ui.item.itemid + ',' + ui.item.itemtype + ',' + ui.item.label);
//$("form").submit();
}
});
});

jquery autocomplete get id as selected label

I am using JQuery autocomplete to get data from database in php.
I am getting correct result from database as I type keyword. But, I want id of that data separate (because I don't want id in the label itself). My JQUERY CODE lokks like this:
$( "#referrer" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax/ir_populate_referrer",
dataType: "json",
type: "POST",
data: {
keyword: request.term
},
success: function(data){
response( $.map( data, function( item ) {
//alert(item.label);
return {
label: item.label
}
}));
}
})
}
});
PHP Backend:
$searchArray = array();
while($search = $result->fetch()){
$link = '';
$link .= $search['id'].', '.$search['cus_firstname'].' '.$search['cus_lastname'].', '.$search['cus_email'].', '.$search['cus_phone1'];
array_push($searchArray, array('label'=> $link, 'value' => $keyword, 'id'=>$search['id']));
}
echo json_encode($searchArray);
The problem is how can I put id in html other than label itself, when user selects particular suggestion. I want to put id in this HTML container:
<input type='hidden' name='referrer_id' id='referrer_id' />
$( "#referrer" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax/ir_populate_referrer",
dataType: "json",
type: "POST",
data: {
keyword: request.term
},
success: function(data){
response( $.map( data, function( item ) {
//alert(item.label);
return {
label: item.label,
value: item.value // EDIT
}
}));
}
})
}
select: function(event, ui) {
$("#referrer_id").val(ui.item.value); // ui.item.value contains the id of the selected label
}
});
$("#zipsearch").autocomplete({
source: function(req,res) {
$.ajax({
url: "json.php",
dataType: "json",
type: "GET",
data: {
term: req.term
},
success: function(data) {
res($.map(data, function(item) {
return {
label: item.label,
value: item.value,
id: item.id
};
}));
},
error: function(xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
},
focus: function( event, ui ) {
$( "#zipsearch" ).val( ui.item.label );
return false;
},
select: function(event, ui) {
alert(ui.item.id);
$( "#zipsearch" ).val( ui.item.label );
return false;
}
});
<head runat="server">
<title></title>
<link href="Styles/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui.js" type="text/javascript"></script>
<style>
body
{
font-size: 70%;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/AutoCompleteAjaxRequest",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'prefixText' : '" + $("#<%=TextBox1.ClientID %>").val() + "'}",
success: function (data) {
response($.map($.parseJSON(data.d), function (item) {
return {
label: item.UserNameToShow,
value: item.UserName,
id: item.UserId
}
}))
}
});
},
select: function (event, ui) {
$("#referrer_id").val(ui.item.id); // ui.item.value contains the id of the selected label
}
});
});
</script>

Categories

Resources