0

我有一个 JSON 字符串 {"Name1":"ID1","Name2":"ID2"},就像我使用 PHP 的 json_encode 检索到的一样。如何在自动完成选项中有一个带有 Name1,Name2 的输入字段,并且一旦选择Name1ID1将被置于隐藏字段中?我正在使用 Jquery ui 自动完成功能。

        var NameIDJsonString = <?php echo $NameIDJsonString; ?>;

            $(function () {
                $('#JSONName').autocomplete({

                        source: function (request, response) {
                            response($.map(NameIDJsonString, function (value, key) {
                                return {
                                    label: key,
                                    value: value
                                };
                            }));
                        },
                        select: function (event, ui) {
                            $("#JSONName").val(ui.item.text); // display the selected text
                            $("#JSONID").val(ui.item.value); // save selected id to hidden input
                        }
                    });
                });            
    }                       

<html>
<body>
                                 <input  id="JSONName" name="JSONName" size="30" class="ui-autocomplete-input" autocomplete="on" type="text" >
                                 <input  id="JSONID" name="JSONID" size="30" class="ui-autocomplete-input" autocomplete="on" type="hidden" >

http://jsfiddle.net/mahesh1393/Aa5nK/4166/

4

1 回答 1

0
                var source  = [ ];
                var mapping = { };
                for(var i = 0; i < NameIDJsonString.length; ++i) {
                    source.push(NameIDJsonString[i].Name);
                    mapping[NameIDJsonString[i].Name] = NameIDJsonString[i].ID;
                }
                $('#JSONName').autocomplete({
                    minLength: 1,
                    source: source,
                    select: function(event, ui) {
                        "use strict";
                        var summary=ui.item.value;
                        $("#JSONID").val(mapping[name]);
                    },
                    change: function( event, ui ) {
                        val = $(this).val();
                        exists = $.inArray(val,source);
                        if (exists<0) {
                            $(this).val("");
                            alert("Please enter a value from the list");
                        return false;
                        }
                    }
                });

我已将我的 JSON 字符串修改为每个对象,例如

{Name:"Name1",ID:"ID1"}
{Name:"Name2",ID:"ID2"} 

因此上面的代码会有所帮助。谢谢。:)

于 2018-08-14T20:06:52.817 回答