Javascript 带有项目和 id 的 jQuery UI 自动完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4815330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:15:00  来源:igfitidea点击:

jQuery UI autocomplete with item and id

javascriptjqueryarraysjquery-uijquery-ui-autocomplete

提问by oshirowanen

I have the following script which works with a 1 dimensional array. Is it possible to get this to work with a 2 dimensional array? Then whichever item is selected, by clicking on a second button on the page, should display the id of whichever item is selected.

我有以下脚本可用于一维数组。是否有可能让它与二维数组一起工作?然后无论选择哪个项目,通过单击页面上的第二个按钮,都应显示所选项目的 id。

This is the script with the 1 dimensional array:

这是具有一维数组的脚本:

var $local_source = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"];
$("#txtAllowSearch").autocomplete({
    source: $local_source
});

This is the script for the button to check the id, which is incomplete:

这是按钮检查id的脚本,不完整:

$('#button').click(function() {
    // alert($("#txtAllowSearch").someone_get_id_of_selected_item);
});

回答by JK.

You need to use the ui.item.label (the text) and ui.item.value (the id) properties

您需要使用 ui.item.label(文本)和 ui.item.value(id)属性

$('#selector').autocomplete({
    source: url,
    select: function (event, ui) {
        $("#txtAllowSearch").val(ui.item.label); // display the selected text
        $("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
    }
});

$('#button').click(function() {
    alert($("#txtAllowSearchID").val()); // get the id from the hidden input
}); 

[Edit] You also asked how to create the multi-dimensional array...

[编辑]您还询问了如何创建多维数组...

You should be able create the array like so:

您应该能够像这样创建数组:

var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"], 
                     [4,"javascript"], [5,"asp"], [6,"ruby"]];

Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml

在此处阅读有关如何使用多维数组的更多信息:http: //www.javascriptkit.com/javatutors/literal-notation2.shtml

回答by Salman A

From the Overview tab of jQuery autocomplete plugin:

从 jQuery 自动完成插件的概览选项卡:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

本地数据可以是一个简单的字符串数组,或者它包含数组中每个项目的对象,带有标签或值属性或两者兼而有之。label 属性显示在建议菜单中。在用户从菜单中选择某些内容后,该值将被插入到 input 元素中。如果只指定了一个属性,它将用于两者,例如。如果您仅提供 value-properties,则该值也将用作标签。

So your "two-dimensional" array could look like:

所以你的“二维”数组可能看起来像:

var $local_source = [{
    value: 1,
    label: "c++"
}, {
    value: 2,
    label: "java"
}, {
    value: 3,
    label: "php"
}, {
    value: 4,
    label: "coldfusion"
}, {
    value: 5,
    label: "javascript"
}, {
    value: 6,
    label: "asp"
}, {
    value: 7,
    label: "ruby"
}];

You can access the label and value properties inside focusand selectevent through the uiargument using ui.item.labeland ui.item.value.

您可以通过使用and的参数访问focusselectevent 中的 label 和 value 属性。uiui.item.labelui.item.value

Edit

编辑

Seems like you have to "cancel" the focus and select events so that it does not place the id numbers inside the text boxes. While doing so you can copy the value in a hidden variable instead. Here is an example.

似乎您必须“取消”焦点并选择事件,以便它不会将 id 号放在文本框中。这样做时,您可以复制隐藏变量中的值。这是一个例子

回答by Paty Lustosa

My code only worked when I added 'return false' to the select function. Without this, the input was set with the right value inside the select function and then it was set to the id value after the select function was over. The return false solved this problem.

我的代码仅在我向 select 函数添加“return false”时才起作用。如果没有这个,输入在 select 函数中设置了正确的值,然后在 select 函数结束后将其设置为 id 值。return false 解决了这个问题。

$('#sistema_select').autocomplete({

    minLength: 3,
    source: <?php echo $lista_sistemas;?> ,
    select: function (event, ui) {
         $('#sistema_select').val(ui.item.label); // display the selected text
         $('#sistema_select_id').val(ui.item.value); // save selected id to hidden input
         return false;
     },
    change: function( event, ui ) {
        $( "#sistema_select_id" ).val( ui.item? ui.item.value : 0 );
    } 
});

In addition, I added a function to the change event because, if the user writes something in the input or erases a part of the item label after one item was selected, I need to update the hidden field so that I don′t get the wrong (outdated) id. For example, if my source is:

另外,我在 change 事件中添加了一个函数,因为如果用户在输入中写了一些东西或者在选择了一个项目后擦除了项目标签的一部分,我需要更新隐藏字段,这样我就不会得到错误(过时)的 ID。例如,如果我的来源是:

var $local_source = [
       {value: 1,  label: "c++"}, 
       {value: 2,  label: "java"}]

and the user type ja and select the 'java' option with the autocomplete, I store the value 2 in the hidden field. If the user erase a letter from 'java', por exemple ending up with 'jva' in the input field, I can′t pass to my code the id 2, because the user changed the value. In this case I set the id to 0.

并且用户键入 ja 并选择带有自动完成功能的“java”选项,我将值 2 存储在隐藏字段中。如果用户从“java”中删除一个字母,例如在输入字段中以“jva”结尾,我无法将 id 2 传递给我的代码,因为用户更改了值。在这种情况下,我将 id 设置为 0。

回答by Benjohn P. Villedo

Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method

只是想分享对我有用的东西,以防它也能帮助其他人。或者,基于 Paty Lustosa 上面的回答,请允许我添加另一种源自该站点的方法,在该站点中,他对源方法使用了 ajax 方法

http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3

http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3

The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:

踢球者是来自您的 php 脚本(下面的 listing.php)的结果“字符串”或 json 格式,它派生出要在自动完成字段中显示的结果集,应遵循以下内容:

    {"list":[
     {"value": 1, "label": "abc"},
     {"value": 2, "label": "def"},
     {"value": 3, "label": "ghi"}
    ]}

Then on the source portion of the autocomplete method:

然后在自动完成方法的源部分:

    source: function(request, response) {
        $.getJSON("listing.php", {
            term: request.term
        }, function(data) {                     
            var array = data.error ? [] : $.map(data.list, function(m) {
                return {
                    label: m.label,
                    value: m.value
                };
            });
            response(array);
        });
    },
    select: function (event, ui) {
        $("#autocomplete_field").val(ui.item.label); // display the selected text
        $("#field_id").val(ui.item.value); // save selected id to hidden input
        return false;
    }

Hope this helps... all the best!

希望这会有所帮助...一切顺利!

回答by Nattrass

Assuming the objects in your source array have an id property...

假设源数组中的对象具有 id 属性...

var $local_source = [
    { id: 1, value: "c++" },
    { id: 2, value: "java" },
    { id: 3, value: "php" },
    { id: 4, value: "coldfusion" },
    { id: 5, value: "javascript" },
    { id: 6, value: "asp" },
    { id: 7, value: "ruby" }];

Getting hold of the current instance and inspecting its selectedItem property will allow you to retrieve the properties of the currently selceted item. In this case alerting the id of the selected item.

获取当前实例并检查其 selectedItem 属性将允许您检索当前选择项的属性。在这种情况下,提醒所选项目的 id。

$('#button').click(function() {
    alert($("#txtAllowSearch").autocomplete("instance").selectedItem.id;
});

回答by Eric Rohlfs

<script type="text/javascript">
$(function () {
    $("#MyTextBox").autocomplete({
        source: "MyDataFactory.ashx",
        minLength: 2,
        select: function (event, ui) {
            $('#MyIdTextBox').val(ui.item.id);
            return ui.item.label;
        }
    });
});

The above responses helped but, did not work in my implementation. The instead of using setting the value using jQuery, I am returning the value from the function to the select option.

上述回应有所帮助,但在我的实施中不起作用。我没有使用 jQuery 设置值,而是将值从函数返回到选择选项。

The MyDataFactory.ashx page has a class with three properties Id, Label, Value.

MyDataFactory.ashx 页面有一个具有三个属性 Id、Label、Value 的类。

Pass the List into the JavaScript serializer, and return the response.

将 List 传递到 JavaScript 序列化程序,并返回响应。

回答by Aadil Masavir

At last i did it Thanks alot friends, and a special thanks to Mr https://stackoverflow.com/users/87015/salman-abecause of his code i was able to solve it properly. finally my code is looking like this as i am using groovy grails i hope this will help somebody there.. Thanks alot

最后我做到了,谢谢很多朋友,特别感谢https://stackoverflow.com/users/87015/salman-a先生, 因为他的代码我能够正确解决它。最后我的代码看起来像这样,因为我使用的是 groovy grails 我希望这会帮助那里的人..非常感谢

html code looks like this in my gsp page

html 代码在我的 gsp 页面中看起来像这样

  <input id="populate-dropdown" name="nameofClient" type="text">
  <input id="wilhaveid" name="idofclient" type="text">

script Function is like this in my gsp page

我的gsp页面中的脚本功能是这样的

  <script>
        $( "#populate-dropdown").on('input', function() {
            $.ajax({
                url:'autoCOmp',
                data: {inputField: $("#populate-dropdown").val()},
                success: function(resp){
                    $('#populate-dropdown').autocomplete({
                        source:resp,
                        select: function (event, ui) {
                            $("#populate-dropdown").val(ui.item.label);
                            $("#wilhaveid").val(ui.item.value);
                             return false;
                        }
                    })
                }
            });
        });
    </script>

And my controller code is like this

我的控制器代码是这样的

   def autoCOmp(){
    println(params)
    def c = Client.createCriteria()
    def results = c.list {
        like("nameOfClient", params.inputField+"%")
    }

    def itemList = []
    results.each{
        itemList  << [value:it.id,label:it.nameOfClient]
    }
    println(itemList)
    render itemList as JSON
}

One more thing i have not set id field hidden because at first i was checking that i am getting the exact id , you can keep it hidden just put type=hidden instead of text for second input item in html

还有一件事我没有将 id 字段设置为隐藏,因为起初我正在检查我是否获得了确切的 id,您可以将其隐藏,只需在 html 中为第二个输入项放置 type=hidden 而不是文本

Thanks !

谢谢 !

回答by HIR

I've tried above code displaying (value or ID) in text-box insted of Label text. After that I've tried event.preventDefault() it's working perfectly...

我已经尝试在标签文本的文本框中显示(值或 ID)上面的代码。在那之后我试过 event.preventDefault() 它工作得很好......

var e = [{"label":"PHP","value":"1"},{"label":"Java","value":"2"}]

$(".jquery-autocomplete").autocomplete({
    source: e,select: function( event, ui ) {
        event.preventDefault();
        $('.jquery-autocomplete').val(ui.item.label);
        console.log(ui.item.label);
        console.log(ui.item.value);
    }
});

回答by Kevin Lee

I do not think that there is need to hack around the value and label properties, use hidden input fields or to suppress events. You may add your own custom property to each Autocomplete object and then read that property value later.

我认为不需要绕过值和标签属性,使用隐藏的输入字段或抑制事件。您可以将自己的自定义属性添加到每个 Autocomplete 对象,然后稍后读取该属性值。

Here is an example.

这是一个例子。

$(#yourInputTextBox).autocomplete({
    source: function(request, response) {
        // Do something with request.term (what was keyed in by the user).
        // It could be an AJAX call or some search from local data.
        // To keep this part short, I will do some search from local data.
        // Let's assume we get some results immediately, where
        // results is an array containing objects with some id and name.
        var results = yourSearchClass.search(request.term);

        // Populate the array that will be passed to the response callback.
        var autocompleteObjects = [];
        for (var i = 0; i < results.length; i++) {
            var object = {
                // Used by jQuery Autocomplete to show
                // autocomplete suggestions as well as
                // the text in yourInputTextBox upon selection.
                // Assign them to a value that you want the user to see.
                value: results[i].name;
                label: results[i].name;

                // Put our own custom id here.
                // If you want to, you can even put the result object.
                id: results[i].id;
            };

            autocompleteObjects.push(object);
        }

        // Invoke the response callback.
        response(autocompleteObjects);
    },
    select: function(event, ui) {
        // Retrieve your id here and do something with it.
        console.log(ui.item.id);
    }
});

The documentationmentions you have to pass in an array of objects with label and value properties. However, you may certainly pass in objects with morethan these two properties and read them later.

文档提到您必须传入具有标签和值属性的对象数组。但是,您可能肯定的物体通过与更多比这两个属性,并在以后读。

Here is the relevant part I am referring to.

这是我所指的相关部分。

Array: An array can be used for local data. There are two supported formats: An array of strings: [ "Choice1", "Choice2" ] An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ] The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.

数组:数组可用于本地数据。有两种支持的格式: 字符串数组: [ "Choice1", "Choice2" ] 具有标签和值属性的对象数组: [ { label: "Choice1", value: "value1" }, ... ] label 属性显示在建议菜单中。当用户选择一个项目时,该值将被插入到 input 元素中。如果只指定了一个属性,它将用于两个属性,例如,如果您只提供值属性,则该值也将用作标签。

回答by Waris Ali

This can be done without the use of hidden field. You have to take benefit of the JQuerys ability to make custom attributes on run time.

这可以在不使用隐藏字段的情况下完成。您必须利用 JQuery 的能力在运行时创建自定义属性。

('#selector').autocomplete({
    source: url,
    select: function (event, ui) {
        $("#txtAllowSearch").val(ui.item.label); // display the selected text
        $("#txtAllowSearch").attr('item_id',ui.item.value); // save selected id to hidden input
    }
});

$('#button').click(function() {
    alert($("#txtAllowSearch").attr('item_id')); // get the id from the hidden input
});