Search code examples
typeahead.jsbootstrap-tags-input

How to create new tags if not present in autocomplete Boostrap tags input typeahead


HTML:

<div class="category-container">
    <input type="text" id="category" />
    <div id='tes'>Check Value
    </div>
</div>

JS:

var data = [{"id":1,"city":"Jakarta"},{"id":2,"city":"Washington"},{"id":3,"city":"Amsterdam"},{"id":4,"city":"Sydney"}]
var citynames = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('city'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: $.map(data, function (city) {
        return {
                id: city.id,
            city: city.city
        };
    })
});
citynames.initialize();

$('.category-container > input').tagsinput({
    typeaheadjs: [{
          minLength: 1,
          highlight: true,
    },{
        minlength: 1,
        name: 'citynames',
        displayKey: 'city',
        valueKey: 'city',
        source: citynames.ttAdapter()
    }]
});
$(document).ready(function(){
    $('#tes').click(function(){
        console.log($('#category').val());
    })
})

If value is present (for example Sydney, then give the input value of ID, in this case 4), but if the value is not present, give the string inputted.

Example: if I input Jakarta and new tag such as Kairo, then the value of input will be 1,Kairo.

How to do this?

Here is the fiddle https://jsfiddle.net/wug8mnss/


Solution

  • There is no builtin feature to do that, but you can easily do it yourself simply by rebuilding the tagsinput val() string, and insert the id of existing values instead of the value itself.

    $('#tes').click(function(){
       var newValues = [], values = $('#category').val().split(',')
       function getVal(value) {
          for (var i=0; i<data.length; i++) {
            if (data[i].city == value) return data[i].id
          }
          return value
       }
       newValues = values.map(function(value) {
         return getVal(value) 
       }).join(',')
       console.log(newValues)
    })
    

    updated fiddle -> https://jsfiddle.net/wug8mnss/2/
    This console out for example

    1, Kairo, 4 
    

    instead of

    Jakarta, Kairo, Sydney