如何操作jquery自动完成插件来获取id和值



我正在使用这个jquery自动完成插件。自动完成的数据格式如下

"name"=>"1" format. 

我只是在下拉列表中显示产品的名称,显示产品id是非常不安全的。但当我提交时,我需要所选产品的id。为此,我试图为输入文本字段提供一个属性,如

input type='text' name='product' productid=''

现在,当用户选择任何产品时,productid属性都应该得到这个值。如何进行此

我想您想要的是select选项。

假设您的数据源是以下对象数组:

var data = [
    {
        label: 'Product 1',
        productid: '1'
    },
    {
        label: 'Product 2',
        productid: '2'
    },{
        label: 'Product 3',
        productid: '1'
    }];

默认情况下,插件将在对象中查找标签属性(如果缺少"值",它将使用"标签")。

注意:如果您提供了一个值,当您在菜单中选择建议项目时,它将用于设置输入的值!

因此,在我们的示例中,属性productid实际上不会被插件直接使用,它不知道它,但我们可以在事件处理程序参数ui.item中访问它。

我想做的是添加一个隐藏字段来存储实际选择的值(而不是像你在问题中建议的属性"productid")。

<input type="hidden" id="productid" value="" />

js代码:

$("#myinput").autocomplete({
    source: data,
    // the 'select' event is triggered when an item is selected in the menu
    select: function(e, ui) {
        $("#productid").val(ui.item.productid);
        // if you want to add the "productid" attiubte
        $(this).attr('productid', ui.item.productid);
    }
});

工作演示

最新更新