Codige follows. This is the first "seems to work" version. The Microsoft AJAX Control Toolkit ComboBox does a good job of providing almost identical functionality, but doesn't always show the "select"/dropdown portion of the pair.


   1 var gintStart = 0;
2 var gintEnd = 0;
3 var gstrLastVal = "";
4
5
6 function findMatch() {
7 frm1 = document.forms[0];
8 intMatch = -1;
9 txtLoc = frm1.elements['txtLoc'];
10 lstLoc = frm1.elements['<%=lstLocs.ClientID%>'];
11
12 var strCurText = txtLoc.value;
13 if (strCurText.length <= gstrLastVal.length) {
14 // ignore all this; allow deletes gracefully
15 } else {
16 //if ( gstrLastVal.length >= 2
17 //&& (0 != txtLoc.value.indexOf(gstrLastVal)) ) {
18 // gets rid of any hanging on autofilled text
19
20
21 if (0 != txtLoc.value.toUpperCase().indexOf(gstrLastVal.toUpperCase())) {
22 // txtLoc.value.slice(0, gstrLastVal.length - 1);
23 // then again let them do what they want. Don't try to overcomplete
24
25 } else {
26 if (txtLoc.value.length > 0) {
27 // go backwards to grab the first match
28 for (var i = lstLoc.options.length - 1; i >= 0; i--) {
29
30 var strOptTxt = lstLoc.options[i].text.toUpperCase();
31
32 if (0 == strOptTxt.indexOf(txtLoc.value.toUpperCase())) {
33 intMatch = i;
34 }
35 }
36
37 if (-1 != intMatch) {
38 lstLoc.options[intMatch].selected = true;
39
40 txtLoc.value = lstLoc.options[intMatch].text;
41 gintStart = strCurText.length;
42 gintEnd = txtLoc.value.length;
43 // (kinda ruining the whitespace to reduce width for blog)
44 //createSelection(txtLoc,strCurText.length,txtLoc.value.length);
45 // it looks like this tries to set the selection while focus is
46 // still going to another control, blowing up the selection.
47 // thus the delay tactics.
48 // unsuccessful delay tactics commented, below.
49 //backdoorSelection();
50 //setTimeout("createSelection(txtLoc,strCurText.length,txtLoc.value.length)",100);
51 //setTimeout("createSelection(txtLoc,4,9)",100);
52 setTimeout("backdoorSelection()", 30);
53 } else {
54 // no match. Deselect anything selected
55 lstLoc.selectedIndex = -1;
56 }
57 }
58 }
59 }
60 gstrLastVal = strCurText;
61 }
62
63 function backdoorSelection() {
64 createSelection(document.forms[0].elements['txtLoc'], gintStart, gintEnd);
65 }
66
67 function createSelection(field, start, end) {
68 if (field.createTextRange) {
69 var selRange = field.createTextRange();
70 selRange.collapse(true);
71 selRange.moveStart('character', start);
72 selRange.moveEnd('character', end);
73 selRange.select();
74 } else if (field.setSelectionRange) {
75 field.setSelectionRange(start, end);
76 } else if (field.selectionStart) {
77 field.selectionStart = start;
78 field.selectionEnd = end;
79 }
80 field.focus();
81 }

Labels: , ,