jQuery Tag-It - 使用值和标签对象列表

seb*_*835 14 jquery label autocomplete tag-it

刚试过优秀的Tag-It!jquery的插件(http://aehlke.github.com/tag-it/),但我无法按照我的意愿去工作.

我有一个像这样的对象列表:

var food = [{value:1,label:'Pizza'},{value:2,label:'Burger'},{value:3,label:'Salad'}];
Run Code Online (Sandbox Code Playgroud)

我在设置中传递给tagSource选项:

$("#my_food_tags").tagit({
    tagSource: food,
    singleField: true,
    singleFieldNode: $("#my_food"),
    placeholderText: "Start typing a food name"
});
Run Code Online (Sandbox Code Playgroud)

这很好用,除非我单击自动完成列表项,它会在标记中显示数字值,而不是食物名称.

因此,可以在隐藏字段中输入"值",并将"标签"显示为标记名称?

这是我的意思的屏幕截图.该值出现在标签标签中,标签丢失到以太;-)

标签文本丢失的示例

有人可以帮我吗?非常感谢!

谢谢,Seb

Mar*_*sen 6

尝试玩弄它,请参阅:http://jsfiddle.net/pDrzx/46/

我做了什么:

使用labelname扩展createTag函数

 createTag: function(labelname, value, additionalClass)
Run Code Online (Sandbox Code Playgroud)

并在标签创建var上调用它

var label = $(this.options.onTagClicked ? '<a class="tagit-label"></a>' : '<span class="tagit-label"></span>').text(labelname);
Run Code Online (Sandbox Code Playgroud)

然后我确保隐藏的输入字段具有数字值(用于保存目的)

  if (this.options.singleField) {
        var tags = this.assignedTags();
        tags.push(value);
        this._updateSingleTagsField(tags);
    } else {
        var escapedValue = value;
        tag.append('<input type="hidden" style="display:none;" value="' + escapedValue + '" name="' + this.options.itemName + '[' + this.options.fieldName + '][]" />');
    }
Run Code Online (Sandbox Code Playgroud)

最后我将标签名添加到自动完成和焦点

        // Autocomplete.
        if (this.options.availableTags || this.options.tagSource) {
            this._tagInput.autocomplete({
                source: this.options.tagSource,
                select: function(event, ui) {
                    // Delete the last tag if we autocomplete something despite the input being empty
                    // This happens because the input's blur event causes the tag to be created when
                    // the user clicks an autocomplete item.
                    // The only artifact of this is that while the user holds down the mouse button
                    // on the selected autocomplete item, a tag is shown with the pre-autocompleted text,
                    // and is changed to the autocompleted text upon mouseup.
                    if (that._tagInput.val() === '') {
                        that.removeTag(that._lastTag(), false);
                    }
                    that.createTag(ui.item.label,ui.item.value);
                    // Preventing the tag input to be updated with the chosen value.
                    return false;
                },
            focus: function(event, ui) {
                event.preventDefault();
                that.createTag(ui.item.label,ui.item.value);
            }
            });
Run Code Online (Sandbox Code Playgroud)

所以什么都没有了,你需要确保它在所有createTag方法中传递labelname,但那不应该太难:)


以焦点更新(@Edwin启发)