开发者

JavaScript predictive input/drop down

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 b开发者_C百科e 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.


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.


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

If I understood correctly, the above should be working for your case.


  1. Use two lists and convert all elements of one of them to lowercase. Then you can covert the text in the field to lowercase, too, before you do the lookup.

  2. onkeydown and onkeyup are invoked for every key, even the cursor keys, shift, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜