Select2 start with input field instead of dropdown

2019-01-21 22:26发布

I use the js library select2. This is a screenshot of what I have now:
Start:
enter image description here
Click on dropdown:
enter image description here

Now is it possible to have an input field to start with and not directly a dropdownlist? I know it's possible because you can find it on the select2 site. An example is this: enter image description here enter image description here

But the documentation is very brief. This is what I have now:

<input type="text" name="questions[question1]" id="question1" class="question1" style="width:500px"/>
function createQuestionTags(data, question_number){
  $(".question" + question_number).select2({
    createSearchChoice: function (term, data) {
      if ($(data).filter(function () {
        return this.text.localeCompare(term) === 0;
      }).length === 0) {
        return {
          id: term,
          text: term
        };
      }
    },
    data: data,
    placeholder: "Enter Question",
    allowClear:true
  });
}

(The data is received from an ajax call)

9条回答
【Aperson】
2楼-- · 2019-01-21 23:05

The only workaround that I could come up with is to use both multiple: true and maximumSelectionSize: 1 when setting up.

Please see my example here: http://jsfiddle.net/DanEtchy/Lnf8j/

查看更多
唯我独甜
3楼-- · 2019-01-21 23:12

Instead of Select2 the better choice would be selectize because Select2 seems dead

The usage is easy:

$('select').selectize(options);

Here is number of examples how to use and customize selectize

查看更多
放荡不羁爱自由
4楼-- · 2019-01-21 23:12

Matt,)

this work

    $('.search-town-flat').select2({
        multiple: true,
        placeholder: "Enter values",
        allowClear: true,
        maximumSelectionLength: 2,
        theme      : "classic"
    }).on('select2:select', function (e) {
        $(this).val([]).trigger('change');
        $(this).val([e.params.data.id]).trigger("change");
    });
查看更多
登录 后发表回答