且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使jQuery自动完成功能变得常见

更新时间:2023-11-21 17:58:46

 功能(elementId,controllerName,actionName,fieldName){$(#" + elementId +").autocomplete({来源:功能(请求,响应){$ .ajax({url:'api/'+ controllerName +'/'+ actionName +'',数据类型:"json",数据: {术语:request.term},成功:功能(数据){response($.map(data,function(val,item){返回 {标签:val [0],值:val [1],fieldName:val.fieldId}}))}})},选择:函数(事件,用户界面){$(#" + elementId +").val(ui.item.fieldName);}});} 

I have an MVC - C# app with jquery autocomplete feature for some text boxes. Each View has autocomplete code, some are for the same field (different views), and some different fields as well.

ex.

  • Invoice\Create View customer text box
  • Payment\Create View customer text box
  • Payment\Create View Invoice Number text box

having autocomplete feature. All working as expected.

Here is a sample code (which is in each view for each control - this is for Customer)

$(document).ready(function () {
    $("#CustomerName").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("GetCustomers", "Invoices")',
                datatype: "json",
                data: {
                    term: request.term
                },
                success: function (data) {
                    response($.map(data, function (val, item) {
                        return {
                            label: val.CustomerName,
                            value: val.CustomerName,
                            CustomerId: val.CustomerId
                        }
                    }))
                }
            })
        },
        select: function (event, ui) {
            $("#CustomerId").val(ui.item.CustomerId);
        }
    });
});

Now what I want is, create a common function in a file in Scripts Folder and call that, along with parameters, whenever I need this autocomplete feature to any control in any view.Is there a way to achieve it?

I tried the $(document).ready function in the view's script section, and few other options, but was unsuccessful.

Please let me know, at least whether this could be done or not

function (elementId,controllerName,actionName,fieldName) {
    $("#"+elementId+"").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: 'api/'+controllerName+'/'+actionName+'',
                datatype: "json",
                data: {
                    term: request.term
                },
                success: function (data) {
                    response($.map(data, function (val, item) {
                        return {
                            label: val[0],
                            value: val[1],
                            fieldName: val.fieldId
                        }
                    }))
                }
            })
        },
        select: function (event, ui) {
            $("#"+elementId+"").val(ui.item.fieldName);
        }
    });
}