Turn a Text Form Element into a drop down / text box

Imagine you have a text box, like this:

Name: [ ]Email: [ ]

You want them to be text boxes that the user can type in, but you also have some default choices to give. For example, I may have an address book in a database and may want to provide an autocomplete function on these fields.

So, I wrote a generic javascript package to be able to do this. I call it, “dropbox”. It allows you to turn any text input element into a text/dropbox element. You just define an array of choices to be displayed. It will show the whole list, onfocus, if the field is empty, but will reduce it’s selection set as the user types. In other words, it acts as an autocomplete selection drop down.

 

NOTE: Read all the way to the end before you implement, the first stab at this isn’t the best. Have to revise this article soon to make it flow better, and add the demo back in. Lost the demo when translating from old server to new.

You can get the source code dropbox.js here:
http://www.modphp.org/dropbox/dropbox.js

And, you should get the CSS file too:
http://www.modphp.org/dropbox/dropbox.css

Here is how to use it:
Code:
<html>
<head><title>Example Drop Down on Text Input</title>
<link rel=”stylesheet” href=”dropbox.css” type=”text/css”>
<script language=”javascript” src=”dropbox.js”></script>
<script language=”javascript”>
<!–

var fnames = new Array;
fnames[fnames.length] = ‘John Smith’;
fnames[fnames.length] = ‘John Johnson’;
fnames[fnames.length] = ‘John Wison’;
fnames[fnames.length] = ‘Chris Smith’;
fnames[fnames.length] = ‘Chris Jones’;
fnames[fnames.length] = ‘Chris William’;

var emails = new Array;
emails[emails.length] = ‘aaabbbb@fakedomain76768768.com’;
emails[emails.length] = ‘aaacccc@fakedomain76768768.com’;
emails[emails.length] = ‘aaadddd@fakedomain76768768.com’;
emails[emails.length] = ‘aaaeeee@fakedomain76768768.com’;
emails[emails.length] = ‘bbbaaaaa@fakedomain76768768.com’;
emails[emails.length] = ‘bbbbbbbb@fakedomain76768768.com’;
emails[emails.length] = ‘bbbccccc@fakedomain76768768.com’;
emails[emails.length] = ‘cccaaaaa@fakedomain76768768.com’;
emails[emails.length] = ‘cccbbbbb@fakedomain76768768.com’;

function local_dropboxInit()
{
dropboxInit(‘fname’, ‘fnames’);
dropboxInit(’email’, ’emails’);
}

// –>
</script>

</head>
<body bgcolor=”white” onLoad=”local_dropboxInit();”>

<form name=”emailform”>
<table><tr>
<td>First Name:</td>
<td><input type=”text” size=”50″ name=”fname” id=”fname” maxlength=”255″ AUTOCOMPLETE=”off”></td>
</tr><tr>
<td>Email:</td>
<td><input type=”text” size=”50″ name=”email” id=”email” maxlength=”255″ AUTOCOMPLETE=”off”></td>
</tr></table>
</form>
</body>
</html>

Notice, AUTOCOMPLETE=”off” in the input definitions, that’s to turn off the browsers autocomplete, since we’re implementing our own. Pretty easy to use, eh? Oh yeah, this isn’t PHP, it’s all Javascript. I was inpired to write it after writing the email autocomplete code using XAJAX. Next on my agenda is to combine this work with that work… in other words, I want to enable XAJAX with dropbox to provide a really powerful feature: server side driven dropboxes on any text element!

Last edited by ChaosCaptain on Tue Sep 20, 2005 3:47 pm; edited 2 times in total

PostPosted: Sat Sep 17, 2005 5:31 am Post subject: Reply with quote
This version is MUCH better and is inpired by the dropbox on Yahoo Mail’s compose form.

Demo here: http://www.modphp.org/dropbox2/

The Email box is a <textarea> that automatically grows in height as you
add emails, a trick I picked up from Yahoo, I thought it was pretty
slick.

When you start type, the choices appear in what I am calling a
“dropbox”. The matching text is bold in the list so it’s easy to see
why it’s a match.. It matches any part of the email, not just from the
beginning.

You can scroll up and down with your arrow keys, which will scroll the
DIV when there are more email on the list than visible.

You can use your mouse to select the name you want.

You can insert as many emails as you want, dropbox just keeps on
working. You can even insert email in the middle of the list, drop box
works on the current cursor position and “knows” where to insert the
selected email.

The dropbox is NOT using AJAX. I am loading the emails much like Yahoo
does, by adding
<script language=”javascript” src=”emailjs.php”></script>
which could easily be dynamically made to be:
<script language=”javascript” src=”emailjs.php?version=4″></script>
where 4 is an ever increasing number, everytime you change your address
book, the version number increments for you. This keeps you browser
from caching it.

There are 625 emails loaded in my address book, so it take a second to
load, goto http://www.modphp.org/dropbox2/emailjs.php to see the
output.

When the dropbox appears, the first row is auto selected, so you can
either continue typing or hit TAB or ENTER to select the first choice.

dropbox.css
Code:

.droprow {
background-color: white;
border: 0px;
}
.droptd {
font-size: 12px;
cursor: default;
}
.droprow_highlight {
background-color: #00cccc;
border: 1px outset blue;
}

dropbox.js
Code:

// +————————————————————————+
// | dropbox |
// +————————————————————————+
// | Copyright (c) 2005 David Koopman |
// | Authors David Koopman |
// | Web http://www.modphp.org/ |
// +————————————————————————+
// | This source file is freeware. You must keep this header in tact, |
// | but are free to modify the source and use in any non-profit or |
// | commercial application. |
// +————————————————————————+

var dropboxselectedRow = -1;
var dropboxNumRows = 0;
var dropboxAnchor;
var dropboxChoices = new Array();
var dropboxChoicesDisplayed = new Array();
var dropboxTextRange;
var dropboxTimer;
var dropboxSortVal;

function dropbox_sort(a,b)
{
a = a.toLowerCase();
b = b.toLowerCase();
var ai = (dropboxSortVal && a) ? a.indexOf(dropboxSortVal) : -1 ;
var bi = (dropboxSortVal && b) ? b.indexOf(dropboxSortVal) : -1 ;

// had to add the try catch for IE, which kept bugging out here:
if ( ai==-1 && bi==-1)
{
try {
return a<b ? -1 : (a>b ? 1 : 0);
}
catch (e) {
return 0;
}
}
else if ( ai==-1 )
return 1;
else if ( bi==-1 )
return -1;
else
return ai<bi ? -1 : (ai>bi ? 1 : 0);
}

function dropbox_clearbox()
{
// GET RID OF ANY OTHER BOX FIRST:
var dropbox = document.getElementById(‘dropbox’);
if ( dropbox )
{
document.getElementsByTagName(‘body’)[0].removeChild(dropbox);
}
}

// anchor must be the id of a text input form element
// choices must be an array of strings to choose from
// optionally, you may call this function and set anchor and/or choices to null
// and this function operates as a clearDropbox function… will remove it.
function dropbox(anchor, choices)
{
dropbox_clearbox();

if ( choices == null || choices.length == 0 ) {
dropboxselectedRow = -1;
dropboxNumRows = 0;
//dropboxAnchor = null;
//dropboxChoices = new Array();
return;
}
// set the global vars:
dropboxChoices = choices;
dropboxAnchor = anchor;

// get the anchor object:

anchor = document.getElementById(anchor);
if ( ! anchor )
return;

var val = anchor.value.toLowerCase();
if ( val.length == 0 )
return;

// fix this for IE:
if ( document.all )
{
var t1 = dropboxTextRange;
if ( t1.findText(“,”, -10000) )
{
// t1.setEndPoint(“StartToEnd”, t1);
var bookmark = t1.getBookmark();
var t2 = anchor.createTextRange();
t1 = anchor.createTextRange();
t1.moveToBookmark(bookmark);
t1.setEndPoint(“StartToEnd”, t1);
t1.setEndPoint(“EndToEnd”, t2);
}
else
t1 = anchor.createTextRange();
val = t1.text.toLowerCase();
val = val.replace(/^ +/, ”);
val = val.replace(/ +$/, ”);
}
else
{
if ( val.substring(0, dropboxTextRange+1).indexOf(“,”) == -1 )
val = val.substring(0, dropboxTextRange+1);
else
{
var x = val.substring(0, dropboxTextRange).lastIndexOf(“,”)+1;
val = val.substring(x, dropboxTextRange+1);
val = val.replace(/^ +/, ”);
val = val.replace(/ +$/, ”);
}
}

if ( val.length == 0 )
return true;

var dropbox = document.createElement(‘div’);
dropbox.setAttribute (‘id’ , ‘dropbox’);

document.getElementsByTagName(‘body’)[0].appendChild(dropbox);
dropbox = document.getElementById(‘dropbox’);
dropbox_style = (document.all) ? document.all[‘dropbox’].style : document.getElementById(‘dropbox’).style;

dropbox_style.display = ‘none’;
dropbox_style.border = ‘2px inset blue’;
dropbox_style.position = ‘absolute’;
dropbox_style.backgroundColor = ‘white’;
dropbox_style.padding = ‘2px’;
dropbox_style.width = anchor.offsetWidth+’px’;

var toppos = anchor.offsetTop + anchor.offsetHeight;
var leftpos = anchor.offsetLeft;

anchor = anchor.offsetParent;
while (anchor.tagName != ‘BODY’) {
leftpos += anchor.offsetLeft;
toppos += anchor.offsetTop;
anchor = anchor.offsetParent;
}

dropbox_style.left = leftpos+’px’;
dropbox_style.top = toppos+’px’;
var cnt = 0;
dropboxChoicesDisplayed = new Array;
dropboxSortVal = val;
// dropboxChoices.sort(dropbox_sort);
// first figure out which ones we’re going to display, then sort that list
for (var i=0; i<dropboxChoices.length; i++)
{
if ( dropboxChoices[i].toLowerCase().indexOf(val) != -1 )
{
dropboxChoicesDisplayed[dropboxChoicesDisplayed.length] = dropboxChoices[i];
cnt++;
}
if ( cnt > 25 )
break;
}
dropboxChoicesDisplayed.sort(dropbox_sort);

// Now build the string
var str = ‘<table width=”100%”>’;
for (i=0; i<dropboxChoicesDisplayed.length; i++)
{
str += ‘<tr id=”droprow’+i+'” class=”droprow” onMouseOver=”highlightRow(‘+i+’)” onClick=”dropboxSelect(‘+i+’)”><td id=”droptd’+i+'” class=”droptd”>’;
str += dropbox_markup(dropboxChoicesDisplayed[i], val);
str += ‘</td></tr>’;
}
str += ‘</table>’;
dropbox.innerHTML = str;
dropboxNumRows = cnt;
if ( dropboxNumRows > 0 )
{
dropbox_style.display = ‘inline’;
if ( dropbox.offsetHeight > 200 )
{
dropbox_style.height = ‘200px’;
dropbox_style.overflow = ‘auto’;
}
}
dropboxselectedRow = 0;
highlightRow(dropboxselectedRow);
}

function dropbox_markup( haystack, needle )
{
haystack = dropbox_htmlspecialchars(haystack);
eval(“var reg = /(“+needle+”)/gi”);
return haystack.replace(reg, ‘<b>$1</b>’);
}

function dropbox_del()
{
dropbox();
}

var dktemp1 = false;
function dropboxSelect(i)
{
var anchor = document.getElementById(dropboxAnchor);
if ( ! anchor )
return;
if ( document.all )
{
var t1;
var t2 = dropboxTextRange;
if ( t2.findText(“,”, -10000) )
{
// t1.setEndPoint(“StartToEnd”, t1);
var bookmark = t2.getBookmark();
t1 = anchor.createTextRange();
t2 = anchor.createTextRange();
t2.moveToBookmark(bookmark);
t2.setEndPoint(“StartToEnd”, t2);
t2.setEndPoint(“EndToEnd”, t1);
}
else
t2 = anchor.createTextRange();

t1 = anchor.createTextRange();
t1.setEndPoint(“EndToStart”, t2);

//var t3 = anchor.createTextRange();
//t3.setEndPoint(“StartToEnd”, t2);

var val = t1.text + ” “+ dropboxChoicesDisplayed[i]+”, “;
anchor.value = val;

dropbox(); // this removes the dropbox from the page

t1 = anchor.createTextRange();
t1.setEndPoint(“StartToEnd”, t1);
t1.select();
t1.collapse(false);
dktemp1 = true;
return true;

}
else
{

var val = anchor.value;

if ( val.substring(0, dropboxTextRange+1).indexOf(“,”) == -1 )
val = dropboxChoicesDisplayed[i] + “, “+ val.substring(dropboxTextRange+1, val.length);
else
{
var x = val.substring(0, dropboxTextRange).lastIndexOf(“,”)+1;
val = val.substring(0, x)+” “+dropboxChoicesDisplayed[i]+”, “+val.substring(dropboxTextRange+1, val.length);
}
anchor.value = val;
// anchor.focus();
//dropboxTextRange = document.getElementById(dropboxAnchor).selectionStart;
}

var tempChoices = dropboxChoices;
var tempAnchor = dropboxAnchor;
dropbox(); // this removes the dropbox from the page
dropboxChoices = tempChoices;
dropboxAnchor = tempAnchor;
anchor.focus();
if ( document.all )
dropboxTextRange = document.selection.createRange();
else
dropboxTextRange = document.getElementById(dropboxAnchor).selectionStart;
}

function highlightRow( i )
{
for (var j=0; j<dropboxNumRows; j++)
{
if ( j != i )
document.getElementById(‘droprow’+j).className = ‘droprow’;
else {
var droprow = document.getElementById(‘droprow’+j);
droprow.className = ‘droprow_highlight’;
var offset = droprow.offsetTop + droprow.offsetHeight;
var dbox = document.getElementById(‘dropbox’);
var clientHeight = parseInt( dbox.clientHeight );
var scrollHeight = parseInt( dbox.scrollHeight );
var scrollTop = parseInt( dbox.scrollTop );

if ( clientHeight + scrollTop < offset )
{
dbox.scrollTop += droprow.offsetHeight+2;
}
else if ( scrollTop + droprow.offsetHeight > offset )
{
dbox.scrollTop -= droprow.offsetHeight+2;
}
}

}
dropboxselectedRow = i;
}

function dropboxKeystroke(e)
{
if ( e == null )
e = window.event;
var key = ( e.keyCode > 0 ? e.keyCode : e.which );
// if down or up arrow, move up or down the list instead!
if ( key == 40 ) // down
{
// down arrow clicked, let’s move down the list:
// document.getElementById(‘outdiv’).innerHTML += ” “+dropboxselectedRow+”,”+dropboxNumRows; // debug line
if ( dropboxselectedRow+1 < dropboxNumRows )
{
highlightRow(dropboxselectedRow+1);
}
return false;
}
else if ( key == 38 ) // up
{
// up arrow clicked, let’s move up the list:
if ( dropboxselectedRow > 0 )
{
highlightRow(dropboxselectedRow-1);
}
return false;
}
else if ( key == 13 || key == 9 ) // ENTER KEY
{
if ( dropboxselectedRow > -1 )
{
dropboxSelect(dropboxselectedRow);
}
return false;
}
else if ( key == 37 || key == 39 )
return true;

//if ( dropboxTimer )
// clearTimeout( dropboxTimer );
//dropbox_clearbox();
if ( document.all )
dropboxTextRange = document.selection.createRange();
else if ( dropboxAnchor )
dropboxTextRange = document.getElementById(dropboxAnchor).selectionStart;
else
return;

//dropboxTimer = setTimeout(“dropbox(dropboxAnchor, dropboxChoices);”, 5);
setTimeout(“dropbox(dropboxAnchor, dropboxChoices);”, 10);
//dropbox(dropboxAnchor, dropboxChoices);

}

function dropboxInit(elementId, choiceArray)
{
//document.getElementById(elementId).onfocus = function() { setTimeout(“dropbox(‘”+elementId+”‘, “+choiceArrayName+”);”, 1); };

document.getElementById(elementId).onfocus = function() { dropbox(); dropboxChoices = choiceArray; dropboxAnchor = elementId; };
document.getElementById(elementId).onblur = function() { setTimeout(‘dropbox()’, 200); }
if ( document.all )
document.getElementById(elementId).onkeydown = dropboxKeystroke;
else
document.getElementById(elementId).onkeypress = dropboxKeystroke;
}

function dropbox_htmlspecialchars(input)
{
input = input.replace(/&/g, ‘&’);
input = input.replace(/</g, ‘<‘);
input = input.replace(/>/g, ‘>’);
input = input.replace(/”/g, ‘”‘);
input = input.replace(/’/g, ”’);
return input;
}

function dropbox_unhtmlspecialchars(input)
{
input = input.replace(/</g, ‘<‘);
input = input.replace(/>/g, ‘>’);
input = input.replace(/”/g, ‘”‘);
input = input.replace(/’/g, “‘”);
input = input.replace(/&/g, “&”);
return input;
}

function dropbox_striphtml(input)
{
input = input.replace(/<.*>/g, ”);
return input;
}

emailjs.php
Code:

<?php
header(“Content-Type: application/x-javascript”);

require_once(“DB.php”);
define(‘DSN’, ‘mysql://email:xxxxx@localhost/email2’);

function fetchEmails($limit=1000)
{
$aDB = DB::connect(DSN);
if ( DB::isError($aDB) )
return;
$aDB->setFetchMode(DB_FETCHMODE_ASSOC);

$email = $aDB->quote($email);
$email = ereg_replace(“^'”, “”, $email);
$email = ereg_replace(“‘$”, “”, $email);

$aSQL = “SELECT concat(display_name, ‘ <‘, email, ‘>’) as email FROM email WHERE email<>” ORDER BY email LIMIT “.$aDB->quote((int)$limit);
$aResult = $aDB->query($aSQL);
if ( DB::isError($aResult) )
return array();
$emails = array();
while ($aRow = $aResult->fetchRow() )
{
$aRow[’email’] = trim($aRow[’email’]);
if ( ereg(“^<“, $aRow[’email’]) )
$aRow[’email’] = preg_replace(array(“/</”, “/>/”), array(“”, “”), $aRow[’email’]);
$emails[] = $aRow[’email’];
}

#natcasesort($emails);
return $emails;
}

function jsAddSlashes($str) {
$pattern = array(
“/\\\\/” , “/\n/” , “/\r/” , “/\”/” ,
“/\’/” , “/&/” /* , “/</” , “/>/” */
);
$replace = array(
“\\\\\\\\”, “\\n” , “\\r” , “\\\”” ,
“\\'” , “\\x26” /*, “\\x3C” , “\\x3E” */
);
return preg_replace($pattern, $replace, $str);
}

$emails = fetchEmails(2500);
print “var emails = new Array;\n”;
foreach ($emails as $email)
print “emails[emails.length] = ‘”.jsAddSlashes($email).”‘;\n”;

?>

index.php
Code:

<html>
<head><title>Example Drop Down on Text Input</title>
<link rel=”stylesheet” href=”dropbox.css” type=”text/css”>
<link rel=”stylesheet” href=”text_textarea.css” type=”text/css”>
<script language=”javascript” src=”dropbox.js”></script>
<script language=”javascript” src=”text_textarea.js”></script>
<script language=”javascript” src=”emailjs.php”></script>
<script language=”javascript”>
<!–

function local_init()
{
text_textarea_ehandlers(’emailto’)
dropboxInit(’emailto’, emails);
}

// –>
</script>

</head>
<body bgcolor=”white” onLoad=”local_init();”>

<form name=”emailform”>
<table width=600><tr>
<td width=50>Email:</td>
<td><textarea id=”emailto” name=”emailto” rows=”1″ cols=”80″ class=”text_textarea”></textarea></td>
</tr></table>
</form>

Here are the names I used to create the email addresses, so you know what to practice with:
<BR><BR>

$name[] = ‘allison’;<br>
$name[] = ‘berry’;<br>
$name[] = ‘cambell’;<br>
$name[] = ‘david’;<br>
$name[] = ‘ebert’;<br>
$name[] = ‘frank’;<br>
$name[] = ‘heather’;<br>
$name[] = ‘ingrid’;<br>
$name[] = ‘jack’;<br>
$name[] = ‘jones’;<br>
$name[] = ‘keri’;<br>
$name[] = ‘lincon’;<br>
$name[] = ‘marvin’;<br>
$name[] = ‘newman’;<br>
$name[] = ‘owen’;<br>
$name[] = ‘paul’;<br>
$name[] = ‘quil’;<br>
$name[] = ‘randy’;<br>
$name[] = ‘smith’;<br>
$name[] = ‘taylor’;<br>
$name[] = ‘ulman’;<br>
$name[] = ‘vincent’;<br>
$name[] = ‘william’;<br>
$name[] = ‘young’;<br>
$name[] = ‘zimm’;<br>

</body>
</html>

insert_emails.php
Code:

<?php
require_once(“DB.php”);
define(‘DSN’, ‘mysql://email:xxxxx@localhost/email2’);
$aDB = DB::connect(DSN);
$aDB->setFetchMode(DB_FETCHMODE_ASSOC);
$domain = ‘fd843481.com’;

$name[] = ‘allison’;
$name[] = ‘berry’;
$name[] = ‘cambell’;
$name[] = ‘david’;
$name[] = ‘ebert’;
$name[] = ‘frank’;
$name[] = ‘heather’;
$name[] = ‘ingrid’;
$name[] = ‘jack’;
$name[] = ‘jones’;
$name[] = ‘keri’;
$name[] = ‘lincon’;
$name[] = ‘marvin’;
$name[] = ‘newman’;
$name[] = ‘owen’;
$name[] = ‘paul’;
$name[] = ‘quil’;
$name[] = ‘randy’;
$name[] = ‘smith’;
$name[] = ‘taylor’;
$name[] = ‘ulman’;
$name[] = ‘vincent’;
$name[] = ‘william’;
$name[] = ‘young’;
$name[] = ‘zimm’;

$loop = count($name);
for ($i=0; $i<$loop; $i++)
{
for ($j=0; $j<$loop; $j++)
{
$email = strtolower($name[$i].$name[$j].”@”.$domain);
if ( rand(0,3)%4 == 0)
$sql = “INSERT INTO email SET display_name=”, email=’$email'”;
else
$sql = “INSERT INTO email SET display_name='”.ucfirst($name[$i]).” “.ucfirst($name[$j]).”‘, email=’$email'”;
$aDB->query($sql);
}
}
?>

text_textarea.css
Code:

.text_textarea {
height: 1.6em;
width:100%;
overflow:visible;
font-family:sans-serif,monospace;
font-size:12px;
}

text_textarea.js
Code:

function text_textarea_ehandlers ( element ) {
if ( typeof element == “string” ) element = document.getElementById ( element );
if ( element == null || element.tagName != “TEXTAREA” )
return;

if ( element.attachEvent ) { // IE
element.attachEvent ( “onfocus”, text_textarea_set_height );
element.attachEvent ( “onkeyup”, text_textarea_set_height );
element.attachEvent ( “onmouseup”, text_textarea_set_height );
element.attachEvent ( “onselect”, text_textarea_set_height );
element.attachEvent ( “oncut”, text_textarea_set_height );
element.attachEvent ( “onpaste”, text_textarea_set_height );

} else if ( element.addEventListener ) { // Moz
element.addEventListener ( “focus”, text_textarea_set_height, true );
element.addEventListener ( “keyup”, text_textarea_set_height, true );
element.addEventListener ( “mouseup”, text_textarea_set_height, true );
element.addEventListener ( “select”, text_textarea_set_height, true );
}
text_textarea_resize(element);
}

function text_textarea_set_height(e)
{
if ( e == null )
e = window.event;
if ( e == null )
return;
var target = e.srcElement ? e.srcElement : e.target ;
if ( target == null )
return;
setTimeout ( “text_textarea_resize(‘” + target.id + “‘)”, 10 );
}

function text_textarea_resize( element ) {
if ( typeof element == “string” ) element = document.getElementById ( element );
if ( element == null || element.tagName != “TEXTAREA” )
return;
if ( element.value.length == 0 ) {
element.style.height = null;
return;
}
var max = 200;
var clientHeight = parseInt( element.clientHeight );
var scrollHeight = parseInt( element.scrollHeight );
if (( Math.abs( clientHeight – scrollHeight ) > 4 ) || ( clientHeight < scrollHeight )) {
scrollHeight += 4; // TEXTAREA frame
if ( scrollHeight > max )
scrollHeight = max;
if ( scrollHeight != element.offsetHeight )
element.style.height = scrollHeight + “px”;
}
}

PostPosted: Tue Sep 20, 2005 3:45 pm Post subject: Reply with quote
This is not in the demo, yet, but just came up with a new way of doing this.

This is code for inside the dropbox function, not the entire dropbox function, just the portion that picks the hits. For this code to work right, you want your emails list already alphabetical. The best way to do this is sort them server side before you give the list to the browser. Here’s the code snippet, I’ll explain afterwards what is better:

Code:

var dropboxNumResultsToDisplay=30;
var x;
var firstArray = new Array;
var secondArray = new Array;
var thirdArray = new Array;
var hasAt = val.indexOf(‘@’) != -1 ? true : false;
for (var i=0; i<dropboxChoices.length; i++)
{
x = dropboxChoices[i].toLowerCase().indexOf(val);
if ( x == 0 )
{
firstArray[firstArray.length] = dropboxChoices[i];
}
else if ( x != -1 )
{
if ( hasAt )
secondArray[secondArray.length] = dropboxChoices[i];
else
{
x = dropboxChoices[i].toLowerCase().indexOf(‘@’+val);
if ( x != -1 )
secondArray[secondArray.length] = dropboxChoices[i];
else
thirdArray[thirdArray.length] = dropboxChoices[i];
}
}
if ( firstArray.length >= dropboxNumResultsToDisplay )
break;
}

dropboxChoicesDisplayed = firstArray;
for (i=0; dropboxChoicesDisplayed.length < dropboxNumResultsToDisplay && i < secondArray.length; i++)
dropboxChoicesDisplayed[dropboxChoicesDisplayed.length] = secondArray[i];
for (i=0; dropboxChoicesDisplayed.length < dropboxNumResultsToDisplay && i < thirdArray.length; i++)
dropboxChoicesDisplayed[dropboxChoicesDisplayed.length] = thirdArray[i];

What is better is:
1) Defined, dropboxNumResultsToDisplay to limit the number of results
2) removed the need for the custom sort function. When looping through all the emails in the array, I am looking for ones that contain what I have typed in the text box so far. When I find a match, I add it to one of three arrays. The firstArray is for matches that start with val. The secondArray is for matches that contain “@”+val. When we’re talking email addresses, this is very useful. The thirdArray is for other matches. So, we put emails that start with val first, that contain “@”+val second, then remaining matches to fill.

The #2 is really a lot better. Removes the need for the user sort function, which ends up saving processing time. Not only do we get a new feature out of this, it’s faster too!

 

Comments are closed.