DataTables

DataTables Examples

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://rawgithub.com/bootstrap-tagsinput/bootstrap-tagsinput/master/dist/bootstrap-tagsinput.js"></script>
<link rel="stylesheet" href="https://rawgithub.com/bootstrap-tagsinput/bootstrap-tagsinput/master/src/bootstrap-tagsinput.css">
<script src="https://rawgithub.com/davidkonrad/Bootstrap-3-Typeahead/master/bootstrap3-typeahead.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/bloodhound.js"></script>
<section id="examples">
  <div class="example example_typeahead">
    <h3>Typeahead</h3>
    <div class="bs-example">
      <input class="testing" type="text" value="3,6" />
    </div>
  </div>
</section>

CSS

body {
  padding: 20px;
  /* optional; just to improve layout */
}

.bootstrap-tagsinput {
  width: 100%;
  /* if you prefer a fixed width, remove above and uncomment the next line */
  /* width: 320px; */
}

JavaScript

var elt = $('.testing');
var data = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('text'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  prefetch: 'https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/assets/cities.json',
  ttl: 1
});

var promise = data.initialize();

promise.done(function() {
  elt.tagsinput({
    itemValue: 'value',
    itemText: 'text',
    typeahead: {
      source: makeCityList(data.index.datums),
      afterSelect: function() {
        // I've no clue why this is needed but as long as it works... ¯\_(ツ)_/¯ 
        this.$element[0].value = '';
      }
    }
  });

  function makeCityList(cities) {
    return $.map(cities, function(item, index) {
      return item;
    });
  }

  function populateValues() {

    var cities = makeCityList(data.index.datums);
    var selectedValues = $('.testing').val().split(',');
    var filtered = [];

    $.each(selectedValues, function(idx, selectedValue) {
      cities.filter(function(ele, idx) {
        if (ele.value === parseInt(selectedValue, 10)) {
          filtered.push(ele)
        }
      });
    });

    // fill input based on selected ids
    $.each(filtered, function(idx, selectedObjects) {
      elt.tagsinput('add', selectedObjects);
    });

  }

  populateValues();
});


promise.fail(function() {
  console.log('err, something went wrong :(');
});