Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript predictive input/drop down

Tags:

javascript

ive got a text input whereby somebody can begin to type and then below the list will populate according to what matches your input.

1) At the moment im using this to check for 'contains':

if(listToRedo[i].value.indexOf(text) != -1){

but the problem is that it appears to be case sensitive, how can i change this?

2) Do onkeyevent, onkeypress, onkeydown accept the delete key action? Also which one is best to use for this activity.

like image 632
Tom Avatar asked Mar 02 '26 15:03

Tom


1 Answers

1) ...but the problem is that it appears to be case sensitive, how can i change this?

You have two options. The first is to convert both strings to lower case, like so:

if (listToRedo[i].value.toLowerCase().indexOf(text.toLowerCase()) != -1) {

or use a regular expression with the case insensitive modifier (i):

var reg = new RegExp(text, "i");
if (listToRedo[i].value.search(reg) != -1) {

This second method can introduce issues, however, if your test string contains characters that have special functions in regular expressions and you will need to escape those characters beforehand. The first method is more appropriate for a basic search.

2) Do onkeyevent, onkeypress, onkeydown accept the delete key action? Also which one is best to use for this activity.

onkeydown and onkeyup will fire for the delete key. onkeypress will not fire for delete key in at least Chrome and IE, for which it will fire for the following keys only:

  • Letters: A - Z (uppercase and lowercase)
  • Numerals: 0 - 9
  • Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~
  • System: ESC, SPACEBAR, ENTER

It's best to use a combination of onkeypress and onkeydown and check for a change in the input's value, as the behaviour of these events differs between browsers.

like image 150
Andy E Avatar answered Mar 04 '26 06:03

Andy E