Friday, September 21, 2007

Change multiple textbox value simultenously

Ever tried duplicating values from one main textbox to another (in XUL)? or to many others? Right after every keypresses from the user? Well, the JavaScript way is to call the onchange / onkeypress / onkeydown / onkeyup event for the main textbox, and when the event occurs, duplicate it's content to the target textboxes.

Well, this is not the same in case of XUL textboxes. Using onchange / onkeypress / onkeydown / onkeyup will always get the second latest char, as illustrated in this example:

Main textbox
-------------------------
| 12345 |
-------------------------

Duplicating textbox
-------------------------
| 1234 |
-------------------------

So the correct way is to use the oninput event handler, then you'll get the latest update from the main textbox.

Sample code:

<textbox id="main" oninput="duplicateValue()" />
<textbox id="duplicate" />

function duplicateValue()
{
var main = document.getElementById('main');
var duplicate = document.getElementById('duplicate');

duplicate.value = main.value;

}

No comments: