bootstrap icon indicating copy to clipboard operation
bootstrap copied to clipboard

Multiple value input in Typeahead

Open suigintou opened this issue 13 years ago • 5 comments

I am need the ability to enter multiple values in Typeahead. This is needed to enter tags, for example. Values can be separated by delimiter symbols or with help of custom tokenizer (optional).

suigintou avatar Dec 22 '12 17:12 suigintou

Cool, but we don't have that. Sorry.

mdo avatar Dec 22 '12 20:12 mdo

I've been using https://github.com/max-favilli/tagmanager for a tagging like feature with use of the typeahead plugin.. it works pretty good for my use case, so it might come in handy for you to

Yohn avatar Dec 23 '12 09:12 Yohn

@Yohn, thank you!

suigintou avatar Dec 24 '12 06:12 suigintou

jQueryUI multiple tag input sample remake:

var split = function (val) {
    return val.split(/\s*[,;]\s*/);
};

var extractLast = function (term) {
    return split(term).pop();
};

$(".tags-box").typeahead({
    source: function (query, process) {
        $.getJSON("/Tags/AutoCompletionList", { term: extractLast(query) }, process);
    },
    updater: function (item) {
        var terms = split(this.query);
        terms.pop();
        terms.push(item);
        terms.push("");
        return terms.join(", ");
    },
    matcher: function (item) {
        return extractLast(this.query).length > 0;
    },
    highlighter: function (item) {
        var query = extractLast(this.query).replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
        return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
            return '<strong>' + match + '</strong>';
        });
    }
});

suigintou avatar Dec 24 '12 18:12 suigintou

I have this (rather ugly) solution using a comma as delimiter. Works nice though!

Look for this.query in the typeahead section (around row 1900) in bootstrap.js. Add something like:

if (this.multiple)
  // element value > last word after comma > trimmed
  this.query = this.$element.val().split(/,/).slice(-1)[0].replace(/^\s\s*/, '').replace(/\s\s*$/, '')

Now in your own JS:

// type ahead multiple support
$('.typeahead-multiple').typeahead({
    multiple: true,
    source: $this.data('source'),
    updater: function(item) {
        var val = '',
            tags = $this.val().split(/,/);
        tags.pop();
        for (var i = 0; i < tags.length; i++) tags[i] = tags[i].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        if (tags.length > 0) val = tags.join(', ') + ', ' + item + ', ';
        else val = item + ', ';
        return val;
    }
});

ghost avatar Mar 05 '13 05:03 ghost