Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn Off Tab for Typeahead.js

I am using a typeahead on one of my text boxes(typeahead.js), and I am trying to turn off the tabbing auto complete. I couldn't find this in the documentation, but perhaps someone knows if/how this is possible?

Any suggestions?

EDIT :

Code used for plug in:

myTypeAhead = $('#txtTypeAhead').typeahead({
            name: 'TypeAhead',
            valueKey: "Value",
            remote: '/ServiceHandlers/myHandler.ashx?Method=Method&Query=%QUERY',
            template: ['<p>{{Value}}</p>'],
            engine: Hogan
        });


        companyCodeTypeAhead.on('typeahead:initialized', function (evt)
        {
            console.log('INIT ' + $(evt.target).val());
        });
        companyCodeTypeAhead.on('typeahead:opened', function (evt)
        {
            console.log('OPEN ' + $(evt.target).val());
        });
        companyCodeTypeAhead.on('typeahead:closed', function (evt)
        {
            console.log('CLOSE ' + $(evt.target).val());
        });
        companyCodeTypeAhead.on('typeahead:selected', function (evt, data)
        {
            console.log('SELECT data==>' + data.Key + ' - ' + data.Value); //selected datum object
        });
        companyCodeTypeAhead.on('typeahead:autocompleted', function (evt, data)
        {
            console.log('AUTOCOMPLETE data==>' + data.Key + ' - ' + data.Value); //selected datum object
        });
like image 239
Barry Tormey Avatar asked May 29 '13 18:05

Barry Tormey


4 Answers

In typeahead.js, ctrl-f this: .on("tabKeyed leftKeyed rightKeyed", this._autocomplete);

Remove tabKeyed from the list of key event handlers.

like image 118
George Avatar answered Nov 18 '22 05:11

George


In typeahead 0.11.1, which is the released version as of 12/9/15:

Locate the following function and comment out the autocomplete line as shown and add the next line, which simulates the escape key behavior causing the right events to be thrown, but needs to have $e.preventDefault(); to prevent the interception of the tab key by the browser bypassing typeahead's logic.

        _onTabKeyed: function onTabKeyed(type, $e) {
            var $selectable;
            if ($selectable = this.menu.getActiveSelectable()) {
                this.select($selectable) && $e.preventDefault();
            } else if ($selectable = this.menu.getTopSelectable()) {
//              this.autocomplete($selectable) && $e.preventDefault(); // <-- Comment out
                this.close() && $e.preventDefault();  // <--- Add this
            }
        },

Hopefully they will make that configurable in a forthcoming release.

like image 38
clearlight Avatar answered Nov 18 '22 06:11

clearlight


I wanted the same thing, autocomplete but have the tab NOT select the first option in the list. This was not possible without hacking the actual package which make it not very maintainable. So I went a different route and added a custom dataset that returns the current query as the first result...

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substrRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        // the typeahead jQuery plugin expects suggestions to a
        // JavaScript object, refer to typeahead docs for more info
        matches.push({
          value: str
        });
      }
    });

    cb(matches);
  };
};
var getLocalSource = function() {
  return function findMatches(query, callback) {
    return callback([{
      'data': query
    }]);
  }
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
  'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
  'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
  'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
  'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
  'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
  'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];

var countries = ["Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"];

$('#the-basics .typeahead').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
}, {
  name: 'local-data',
  display: 'data',
  source: getLocalSource()
}, {
  name: 'states',
  displayKey: 'value',
  source: substringMatcher(states),
  templates: {
    header: '<div class="head">States</div>'
  }
}, {
  name: 'countries',
  displayKey: 'value',
  source: substringMatcher(countries),
  templates: {
    header: '<div class="head">Countries</div>'
  }
});
.tt-dataset .head {
  padding: 15px;
  font-weight: bold;
  background-color: lightgray;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<link href="https://twitter.github.io/typeahead.js/css/examples.css" rel="stylesheet" />

<div id="the-basics">
  <input class="typeahead" type="text" placeholder="Locations">
</div>
like image 1
Artistan Avatar answered Nov 18 '22 05:11

Artistan


We hang up the handler on the input field before calling typeahead

var tt = null; // init variable typeahead
var input_element = $(input);

var p = {
    hint: false,
    highlight: true,
    minLength: 1
};

var ds = {
    name: "namecompleter",
    async: true,
    limit: 10,
    source: function (q, syncProcess, asyncProcess) { ... }
};

// The first element in the drop-down list is not selected if the [Tab] button on the keyboard is pressed
// Hook [onTabKeyed] typeahead
var disableOnTabKeyed = true; // default behavior keyTab
input_element.bind("keydown", function(e) {

    // if select from the drop-down list enable [OnTabKeyed] typeahead
    if( (e.keyCode == 40) || (e.keyCode == 38) ){ // (40 - keyDown) || (38 - keyUp)
        disableOnTabKeyed = false;
    }else if( e.keyCode != 9 ){
        disableOnTabKeyed = true;
    }

    if( disableOnTabKeyed && (e.keyCode == 9) ){ // (9 - keyTab)
        tt.typeahead("close");
        //e.keyCode = 0;
        //e.preventDefault();
        //e.stopPropagation();
    }
});  

tt = input_element.typeahead(p, ds);
like image 1
SAV Avatar answered Nov 18 '22 06:11

SAV