Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

javascript quick search of select dropdown is really slow

Posted on 2007-11-14
Last Modified: 2013-12-13
I am currently using this code to show a dropdown box of all the clients in my database. Currently around 2500.  This box loads instantly on its own.]

            <select name="client_id">

$check_name = $user_fullname;            

            $query = 'SELECT c1.client_name AS c1_client_name, c2.client_name AS c2_client_name, c1.client_surname AS c1_client_surname, c2.client_surname AS c2_client_surname, c1.client_id AS client_id, c1.client_rel_id AS c1_client_rel_id'
. ' FROM client c1'
. ' LEFT JOIN client c2 ON c1.client_rel_id = c2.client_id'
. ' WHERE (c1.client_archive = "0" AND c1.client_rel_id = "") OR (c1.client_archive = 0 AND c1.client_sex = "Male" AND c2.client_sex = "Female") OR (c1.client_archive = "0" AND c1.client_sex = c2.client_sex AND c1.client_id < c2.client_id)'
. ' ORDER BY c1.client_surname, c1.client_name';

$results = mysql_query($query);

while ($row = mysql_fetch_assoc($results)) {

if ($row['c1_client_rel_id'] == '') {
    echo '<option value="' . $row['client_id'] . '">';
    echo $row['c1_client_surname'] . ', ' . $row['c1_client_name'];
    echo "</option>\n";
      } else {
      echo '<option value="' . $row['client_id'] . '">';
    echo $row['c1_client_surname'] . ', ' . $row['c1_client_name'];
    echo ' and ';
    echo $row['c2_client_surname'] . ', ' . $row['c2_client_name'];
    echo "</option>\n";
?><option value=" " selected="selected"> </option>

However, i want to add a quick search box so as you type in letters the dropdown box becomes smaller and smaller with relevant entries.  I have used javascript successfully to do this however it is VERY SLOW. depending on the speed of the pc using the page it can take anywhere between 8-15 seconds to load this page. Baring in mind without the javascript it loads instantly with all 2500 entries in the dropdown.

Please can anyone suggest how i can speed up the javascript or an alternative which is much quicker? Possibly ajax?

Here is the javascript i include in this page:

      include "key_clients.html";


<!-- Original:  Anand Raman (anand_raman@poboxes.com) -->
<!-- Web Site:  http://www.angelfire.com/ar/diduknow -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
function SelObj(formname,selname,textname,str) {
this.formname = formname;
this.selname = selname;
this.textname = textname;
this.select_str = str || '';
this.selectArr = new Array();
this.initialize = initialize;
this.bldInitial = bldInitial;
this.bldUpdate = bldUpdate;

function initialize() {
if (this.select_str =='') {
for(var i=0;i<document.forms[this.formname][this.selname].options.length;i++) {
this.selectArr[i] = document.forms[this.formname][this.selname].options[i];
this.select_str += document.forms[this.formname][this.selname].options[i].value+":"+
else {
var tempArr = this.select_str.split('|');
for(var i=0;i<tempArr.length;i++) {
var prop = tempArr[i].split(':');
this.selectArr[i] = new Option(prop[1],prop[0]);
function bldInitial() {
for(var i=0;i<this.selectArr.length;i++)
document.forms[this.formname][this.selname].options[i] = this.selectArr[i];
document.forms[this.formname][this.selname].options.length = this.selectArr.length;

function bldUpdate() {
var str = document.forms[this.formname][this.textname].value.replace('^\\s*','');
if(str == '') {this.bldInitial();return;}
var j = 0;
pattern1 = new RegExp("^"+str,"i");
for(var i=0;i<this.selectArr.length;i++)
document.forms[this.formname][this.selname].options[j++] = this.selectArr[i];
document.forms[this.formname][this.selname].options.length = j;
document.forms[this.formname][this.selname].options[0].selected = true;
//document.forms[this.formname][this.textname].value = document.forms[this.formname][this.selname].options[0].text;
function setUp() {
obj1 = new SelObj('form2','client_id','client_id_entry');
// menuform is the name of the form you use
// itemlist is the name of the select pulldown menu you use
// entry is the name of text box you use for typing in
//  End -->

And i also add a small text box infront of the dropdown box which i pasted at the top:

  <input type="text" name="client_id_entry" size="20" onKeyUp="javascript:obj1.bldUpdate();">

Any help would be greatly appreciated as this page takes waaaay too long to load.
Question by:drews1f
LVL 18

Accepted Solution

Morcalavin earned 250 total points
ID: 20281376
I don't have php on my system, so I'll have to demonstrate using an xml document instead.  Basically, names.xml would be replaced by a php script that returns xml data, based on the url you provide it.  So the url could be "mydatabaselookup.php?name=" + text.value

Run the test scripts below to get an idea of what I'm talking about.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <script type="text/javascript" src="ajax.js"></script>
     <script type="text/javascript">
             function getData(text)
                  var ajax = new Ajax(
                              method: 'GET',
                              onSuccess: fillData,
                              onFailure: function(){alert('An error occurred')}
            function fillData(xml)
                  document.getElementById('select').options.length = 0;
                  var allNames = xml.responseXML.getElementsByTagName('name');
                  for(var i = 0; i < allNames.length; i++)
                        var option = new Option(allNames[i].getAttribute('value'), allNames[i].getAttribute('value'));
                        document.getElementById('select').options[i] = option;
<input type="text" id="text" onkeyup="getData(this)"/><br/>
<select id="select">
<option value="Bob">Bob</option>
<option value="Dave">Dave</option>
<option value="Steve">Steve</option>
<option value="Tim">Tim</option>
<option value="Bill">Bill</option>
<option value="Charlie">Charlie</option>

/*extern ActiveXObject, XMLHttpRequest, window */

function Ajax(url, options)
      var xmlhttp = false;
      var reqObj =
            function() {return new XMLHttpRequest();},
            function() {return new ActiveXObject("Msxml2.XMLHTTP");},
            function() {return new ActiveXObject("Microsoft.XMLHTTP");},
            function() {return window.createRequest();}
      for(var i = 0; i < reqObj.length; i++)
                  xmlhttp = reqObj[i]();
                  xmlhttp = false;
      reqObj = null;
            var parameters = null;
            xmlhttp.open(options.method, url, true);
            if(options.method == 'POST')
                  parameters = '';
                  for(i=0; i < options.form.length; i++)
                        parameters = parameters + options.form[i].name + "=" + encodeURI(options.form[i].value) + "&";
                        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        xmlhttp.setRequestHeader("Content-length", parameters.length);
                        xmlhttp.setRequestHeader("Connection", "close");      
            xmlhttp.onreadystatechange = function()
                  if(xmlhttp.readyState == 4)
                        if(xmlhttp.status == 200)

<?xml version="1.0"?>
<name value="Tom" />
<name value="Wilson" />

Assisted Solution

DavidBlackledge earned 250 total points
ID: 20306646
Regarding your original Javascript solution's problem, the problem is with your initialize() function.

That gets called with every onkeyup event... the first time it iterates through the entire list to build a bar and semicolon delimited list of the values (this could have been done by building the same string in your PHP code that is building the Option tags and just outputting that already-built string instead of making JavaScript do it).
But the real problem is: EVERY subsequent call then breaks that string down into an array of arrays, and populates selectArr with new Options based on the values in the array of arrays.
It doesn't just populate selectArr once, but it re-populates it with every keystroke.  That code should probably have been within the original "if" statement rather than in that if's "else" statement.

Finally, that step could have been elminated by the PHP as well... ignore the above string building by PHP... build the actual Javascript to create the array of options using the PHP.
Output lines like:
'this.selectArr[i] = new Option(" . $row['client_id'] . "," . $row['c1_client_surname'] . ', ' . $row['c1_client_name'] . ");'
(that's just pseudo-PHP.. I don't know PHP really)
Then throw out all references to "this.initialize()"
Then your page should load almost as instantly as it did before (it will just have generated 2500 more lines of javascript if the user looked at the source of the HTML page)).

That array is never modified, so it's just static and can be created by the PHP with no problem.  Anytime you can shift the calculations to the server side (mainly for static things like this array) the better it will run on the browser.


Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
html input 8 42
Link failure 16 34
Start Auto-download of File when page loads? 1 22
Can anyone see what is the fault in my javascript code? 8 31
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question