如何从AutoComplete jQuery函数中获取所需的值



我的jQuery函数:

<script type="text/javascript">
function Origin(sender, args) {
    $(function () {
        $("#<%=txtInfo.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Webservice.asmx/Get") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    async: false,
                    mustMatch: true,
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                    },
                    failure: function (response) {
                    }
                });
            },
            select: function (e, i) {
                $("#<%=hdnInfo.ClientID %>").val(i.item.val);
                info1()                     
            },                    
            minLength: 0
        }).bind('focus', function () { $(this).autocomplete("search"); });              
        });
   }       
</script>

返回{label:item.split(' - ')[0],val:item.split(' - ')[1]}显示该值与' - '拆分之后:如果值是" ABC-2223"然后返回" ABC"但是,如果值为" A-1 ABC-2223",则它仅返回" A",但我想要" A-1 ABC"。

应用此逻辑。 JSFIDDLE

<script>
    $(function () {
        var items = ["abc-2223", "A-1 abc-2223"];
        $.each(items, function (key, value) {
            var item = value;
            var text = "";
            var chkItem = item.split('-')[0];
            if (chkItem.length == 1) {
                text = item.substring(item.lastIndexOf("-") + 0, item.length);
                text = item.replace(text, "");
            }
            else {
                text = chkItem;
            }
            alert(text);
        });
    });
</script>

update

按您要求更改代码;请更改success函数,如下面的代码。

success: function (data) {
        response($.map(data.d, function (item) {
            //Filter item on condition
            var txtLabel = "";
            var chkItem = item.split('-')[0];
            if (chkItem.length == 1) {
                txtLabel = item.substring(item.lastIndexOf("-") + 0, item.length);
                txtLabel = item.replace(txtLabel, "");
            }
            else {
                txtLabel = chkItem;
            }
            return {
                label: txtLabel,
                val: item.split('-')[1] //you have not specified for value field.
            }
        }))
    },

您的服务器在其响应中发送一个字符串数组(data.d)。

让您的服务器直接返回{"label":"...","val":"..."}对象的数组。

最新更新