Search code examples
jqueryjquery-select2jquery-select2-4

Custom user option input in Select2 4.x?


There is a way to add a custom user input in Select2 without using the tags mode.

This is, create a custom select input preserving the select style, without that inline-block little tags.

Also, I found a lot of answers using AJAX and other out of topic things in which none was a solution to my problem.


Solution

  • There is a easy way to implement this functionality:

    tags: true // let users input his/her own value
    multiple: false // forces the select to keep a true select style
    

    Working fiddle (2016-10-29):

    $("select").select2({
      multiple: false,
      tags: true
    });
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    
    <p>
      <a href="https://jsfiddle.net/odahcam/q096tskj/4/">Original Fiddle by @odahcam</a>
    </p>
    
    <select style="width:100%">
      <option>story</option>
      <option>bug</option>
      <option>task</option>
    </select>