Select2 dropdown but allow new values by user?

The excellent answer provided by @fmpwizard works for Select2 3.5.2 and below, but it will not work in 4.0.0.

Since very early on (but perhaps not as early as this question), Select2 has supported “tagging”: where users can add in their own value if you allow them to. This can be enabled through the tags option, and you can play around with an example in the documentation.

$("select").select2({
  tags: true
});

By default, this will create an option that has the same text as the search term that they have entered. You can modify the object that is used if you are looking to mark it in a special way, or create the object remotely once it is selected.

$("select").select2({
  tags: true,
  createTag: function (params) {
    return {
      id: params.term,
      text: params.term,
      newOption: true
    }
  }
});

In addition to serving as an easy to spot flag on the object passed in through the select2:select event, the extra property also allows you to render the option slightly differently in the result. So if you wanted to visually signal the fact that it is a new option by putting “(new)” next to it, you could do something like this.

$("select").select2({
  tags: true,
  createTag: function (params) {
    return {
      id: params.term,
      text: params.term,
      newOption: true
    }
  },
  templateResult: function (data) {
    var $result = $("<span></span>");

    $result.text(data.text);

    if (data.newOption) {
      $result.append(" <em>(new)</em>");
    }

    return $result;
  }
});

Leave a Comment