Select Multiple Tags From An Autocomplete Dropdown - jQuery Tagcomplete

Select Multiple Tags From An Autocomplete Dropdown - jQuery Tagcomplete

The Tagcomplete jQuery plugin converts the normal input field into a dynamic, customizable tags/tokens input with autocomplete support.

The users are able to select multiple tags/tokens from a predefined dropdown list as they type. Supports both static and dynamic data rendering (via AJAX).

1. Insert the latest version of jQuery library and tagcomplete plugin into the html page.

<link rel="stylesheet" href="src/tagcomplete.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js" 
        integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" 
        crossorigin="anonymous"></script>
<script src="src/tagcomplete.js"></script>

2. Create an input field and define the pre-selected tags in the value attribute.

<input type="text" class="tags_input" value="dog,cat,elephant">

3. Define an array of tags/tokes for the autocomplete list.

const data = [
      'cow',
      'goat',
      'pig',
      'snake',
      'hamster',
      'elephant',
      'lion',
      'tiger',
      'monkey',
      'lizard',
      'bird',
      'crocodile',
      'gazelle',
      'antelope'
];

4. Attach the function to the input field and done.

$(".tags_input").tagComplete(
  autocomplete: {
    data: data
  }
});

5. Default customization options.

$(".tags_input").tagComplete(
  // wether the tagcomplete input should be hidden or not
  hide: false,
  // input limit to start the ajax
  keyLimit: 1,
  // tokenizer
  tokenizer: ",",
  // allows users to insert their own data
  freeInput : true,
  // allows usert to edit the tags input
  freeEdit : true,
  // autocomplete options
  autocomplete: {
    // data
    data: [],
    // ajax options
    ajaxOpts: {
      //url: "",
      method: 'GET',
      dataType: 'json',
      data: {}
    },
    // remote query parameters
    params : function(value){
      return {q: value,lol: 23};
    },
    // proccess data
    proccessData: function(data){
      return data;
    }
  }
  
});

6. Do something after a tag is added or deleted.

$(".tags_input").tagComplete(
  // when a new tag is added
  onAdd: function(data){
    return true;
  },
  // when a tag is deleted
  onDelete: function(data){
    return true;
  }
});

This awesome jQuery plugin is developed by razzbee. For more Advanced Usages, please check the demo page or visit the official website.

  • Publication date: 06.12.2018
  • Source