Question

I am using the bootstrap typeahead.js feature for autocomplete capability for 'state' lookup. How can I best prevent individuals from typing all (and not successfully picking Alaska) before submitting the form?

Was it helpful?

Solution

Typeahead.js does not currently support this behavior.
You can use other libraries better suited for restricted options, for example Select2
However I have working fork of Typeahead that supports this.
See the JQuery example page here:
https://github.com/Svakinn/typeahead.js/blob/typeaheadSimple/Examples.md

OTHER TIPS

Depending on your requirements you could enforce picking from valid options only and clearing any invalid input.

Start with creating a custom source which tracks search results:

    var sync = false;
    var current_results = [];
    var current_q = '';
    var selected_val = '';

    function search(q, sync) {
        current_q = q;
        window.sync = sync;
        engine.search(q, cust_sync);
    }

    function cust_sync(datums) {
      current_results = datums;
      sync(datums);
    }

    $('#typeahead').typeahead(
        {
          highlight: true,
          minLength: 0
        },
        {
            source: search // custom search engine
        }

    );

Then bind select and change event handlers.


    $('#typeahead').bind('typeahead:change', function(ev) {
        var current_val = $('#typeahead').val();
        // user moved cursor out of input without selecting from the menu
        if(current_val != selected_val){
            // current query has search results
            if(current_results.length)
                // change input to the first valid search result
                $('#typeahead').typeahead('val', current_results[0].name); 
            // no results for this query - clear input
            else 
                $('#typeahead').typeahead('val', '');
            }
    });


    $('#typeahead').bind('typeahead:select', function(ev, suggestion) {
        selected_val = $('#typeahead').val(); // keep track of a selected value
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top