Created
December 1, 2014 00:31
-
-
Save stowball/13ffd59dd7b23c70c2a0 to your computer and use it in GitHub Desktop.
Datalist as an autocomplete
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function doAppDatalist() { | |
| appsArray.sort(); | |
| var options = '', | |
| $datainput = $('<input class="apps-input form-control" list="apps-list" placeholder="Search apps" />'), | |
| $datainputFake = $('<input class="apps-input apps-input-fake form-control" placeholder="Search apps" />'), | |
| $datalist = $('<datalist id="apps-list" />'); | |
| for (var i = 0; i < appsArray.length; i++) { | |
| options += '<option value="' + appsArray[i][1] + '" data-index="' + i + '" />\n'; | |
| } | |
| $datalist.append(options); | |
| $datainput.on('input keyup', function(e) { | |
| /* | |
| IE10 shows all of the datalist options if you delete the value, but no longer fires the input event if an option is picked. So, if the user has deleted all input text, re-show and put the focus back in to the fake input so we can start the search process again | |
| */ | |
| if (e.type === 'keyup' && (e.keyCode === 8 || e.keyCode === 46) && this.value.length === 0) { | |
| $datainputFake.removeClass('hidden'); | |
| $datainputFake[0].value = ''; | |
| $datainputFake[0].focus(); | |
| } | |
| else { | |
| for (i = 0; i < appsArray.length; i++) { | |
| if (this.value.toLowerCase() === appsArray[i][1].toLowerCase()) { | |
| appsArray[i][0].click(); | |
| $datainputFake[0].value = ''; | |
| this.value = ''; | |
| this.blur(); | |
| } | |
| } | |
| } | |
| }); | |
| $datainputFake.on('keyup', function() { | |
| $datainputFake.addClass('hidden'); | |
| $datainput[0].value = this.value; | |
| $datainput[0].focus(); | |
| $datainput[0].setSelectionRange(this.value.length + 1, this.value.length + 1); | |
| }); | |
| $('#nav-options-container').append($datainput).append($datalist).append($datainputFake); | |
| }; | |
| doAppDatalist(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment