2

I'm using the bootstrap-typehead function to implement an autocomplete box.

  $(function() {
    var availableTags = [ "test1", "test2","test3",....];


    $('.typeahead').typeahead({
      source: availableTags
    });
  });
});

Whereas this works, free text can also be as input. I've noticed many people wanting this functionality and no good explanation for a solution. What is the best way of modifying this so that entries are only matched to those of availableTags? e.g. if "hello" was entered, it is cleared.

The reason why I want this functionality as opposed to an normal dropdown is that there are thousands of availableTags. Scrolling down a long list seems illogical. Thanks

user47467
  • 1,045
  • 2
  • 17
  • 34
  • What is your expected behaviour? I'm not sure to understand it `free text can also be as input`??? – A. Wolff Nov 24 '15 at 11:49
  • How do you want the value cleared? When the user loses focus on the element? – Jacques Marais Nov 24 '15 at 11:52
  • @JacquesMarais yes. so if a user clicks away from the element when a tag that isnt in availabletags, for example, it is cleared. – user47467 Nov 24 '15 at 11:53
  • @A.Wolff if for example, hello was typed in. it normally is accepted even though its not a part of availableTags. this is what i mean by free text. – user47467 Nov 24 '15 at 11:54

1 Answers1

3

Try something like this:

$(function(){
    var availableTags = [ "test1", "test2","test3",....]; // all data required for typeahead

    $(".typeahead").typeahead({
                        source: availableTags
                    })
                    .blur(function(){
                        if(availableTags.indexOf($(this).val()) === -1) 
                            $(this).val("");
                    });
});

When the user clicks away from the input (loses focus), this checks if the value is inside the array availableTags, and if it's not, it sets the input's value back to empty.

Jacques Marais
  • 2,666
  • 14
  • 33