Your Location is: Home > Jquery

Select2 tagging: add custom text behind new tag

From: Hongkong View: 4269 wittich 

Question

I'm using the select2 tagging feature. Is there an easy way to add a custom text behind a new tag. My intention is, that the user knows that he/she will add the tag.

The result should look something like that eg. in examle of color names, there it could say "new color" after a new tag:

add tag custom text eg new color

$(".js-example-tags").select2({
  tags: true
});
select, pre {
  display: inline-block;
}

.js-example-tags {
  width: 256px;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select class="js-example-tags">
  <option selected="selected">orange</option>
  <option>white</option>
  <option>purple</option>
</select> <pre><== Type new tag into search and click enter</pre>

Best answer

If i understant your logic, you could try this:

$(".js-example-tags").select2({
  tags: true,
  createTag:newtag,
  matcher: matchCustom,
});

function newtag(params, data){
    var term = $.trim(params.term);
    if (term === '') {
      return null;
    }
      return {
      id: term,
      text: term + " (New color)",
      newTag: true // add additional parameters
    }
}

function matchCustom(params, data) {
    // If there are no search terms, return all of the data
    if ($.trim(params.term) === '') {
      return data;
    }

    // Do not display the item if there is no 'text' property
    if (typeof data.text === 'undefined') {
      return null;
    }
    
   // Return `null` if the term should not be displayed
    return null;
}
select, pre {
  display: inline-block;
}

.js-example-tags {
  width: 256px;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select class="js-example-tags">
  <option selected="selected">orange</option>
  <option>white</option>
  <option>purple</option>

</select> <pre><== Type new tag into search and click enter</pre>