在jquery的自动完成功能中添加具有空值的自定义项目

问题描述 投票:0回答:1

使用jQuery's autotomplete widget,如果不符合任何条件,我想添加一项。可以添加该项目,但是我面临的问题是我无法将该项目的值设置为null。我得到的是项目的value,其文字与label

示例代码:

source: function(request, response)
{
    //suggestions prefilled via AJAX...

    var items = [];

    if(suggestions.length)
    {
        for(var i in suggestions)
        {
            var item = suggestions[i];

            item.value = suggestions[i].id;
            item.label = suggestions[i].text;

            items.push(item);
        }
    }
    else
    {
        var item = {
            value : null,
            label : "some text..."
        };

        items.push(item);
    }

    response(items);
}

当我管理选定的项目时,这就是我得到的:

select: function(event, ui)
{
    console.log(ui.item.value);
    //if item's value was set to null, then label
    //if item's value was set to 0, then label
    //if item's value was set to "", then label
    //if item's value was set to 123, then 123
}

EDIT:显然,这在历史的某个时候起作用了...

在具有最新jquery和jquery ui的fiddle中存在此问题,但在具有jquery 1.10.4的this one中是最后一个按我想要的方式运行的jquery ui。

jquery jquery-ui jquery-ui-autocomplete
1个回答
0
投票

简短的答案,当列表中有一项可供选择时,似乎忽略了它。

示例:

https://jsfiddle.net/Twisty/6oa0yg24/2/

$(function() {
  var items = [{
      value: 1,
      label: 'neo'
    },
    {
      value: 2,
      label: 'trinity'
    },
    {
      value: 3,
      label: 'morpheus'
    },
    {
      value: null,
      label: 'smith'
    },
    {
      value: undefined,
      label: 'switch'
    },
    {
      value: "",
      label: 'tank'
    }
  ];

  $("#autocomplete").autocomplete({
    source: items,
    select: function(e, ui) {
      console.log(ui.item.value);
    }
  });
});

如果输入t,将获得一些匹配,然后选择smith,则该值将保留为空。如果键入sm,现在唯一的选择是smith,则将添加“史密斯”作为值。为什么?我不知道,但是我测试了所有三种情况,并且每种情况都可以。可以肯定地归结为以下几行(https://code.jquery.com/ui/1.12.1/jquery-ui.js中的5864-5869):

// reset the term after the select event
// this allows custom select handling to work properly
this.term = this._value();

this.close( event );
this.selectedItem = item;

如果您愿意,我怀疑您可以用Widget Factory覆盖它。

© www.soinside.com 2019 - 2024. All rights reserved.