Cooking with JavaScript & DHTML
Subject:   Simulating onchange events
Date:   2006-02-17 15:39:17
From:   dannyg1
Response to: A little problem with this script

(I thought I had replied to this earlier, but I guess it didn't stick. Here's hoping the formatting doesn't get messed up.)

The basic idea is that you need a scripted trigger to simulate the user making a selection with a mouse. One way to approach it is to add to the typeAheadInfo object (it's already a global, so no need to add more global vars to the mix), and let it preserve a reference to the currently active select element and invoke the event handler function. The typeAheadInfo.reset() function execution is an appropriate time for the simulated onchange action to take place, as its execution signifies that the script is no longer waiting for a continuation of type-ahead entry.

The exact way you'd construct this depends on how you implement the real onchange event handlers in your page. For simplicity of demonstration, I'll assume that the select elements have the following event handler inside their tags:


Here's a dummy handler function you can use to test things out:

function showChange(elem) {
alert("/'onchange/' execution for " + + " with value: " + elem.value + ".");

And here's the modified typeAheadInfo object definition with changes in bold:

var typeAheadInfo = {last:0,
changeEvent:function() {if (this.selectElem) {showChange(this.selectElem)}},

reset:function() {this.last=0; this.accumString=""; this.changeEvent(); this.selectElem=null}

Then, inside the typeAhead() function, add the following statement after the script obtains a reference to the select element:

typeAheadInfo.selectElem = selectElem;

(Incidentally, I also noticed that the processing occurs even when the user types the Tab key to move away from the current select element. To prevent this, add the following statement to the typeAhead() function after the charCode variable is set:

if (charCode == 9) {return}

Not including this statement causes an extra execution of the simulated onchange event, which could slow things down if you're doing some heavy-duty processing for that event.)

One more thing about this entire subject: For accessibility reasons, you probably don't want to rely exclusively on the onchange event (or simulation described here) to process a select element choice. Although not as convenient for users with mice, an extra "Go" button next to the select element may be preferred. This button can also be accessed via keyboard, and eliminates the need for the onchange simulation.