12/11/2021

How to activate some code when a text field changes...

In Notes, we were looking for a text field with type-ahead capabilities. There are several field types that have an onChange event that could be used to simulate type-ahead. Selection fields (radio buttons, check boxes) have an immediate response, but for text fields the user has to leave the field in order to trigger the onChange event. A makeshift solution is to have a button next to the field that contains the onChange code, and the user has to click that button. Not very user-friendly, to say the least...

A colleague of mine pointed me to an article by Hogne Bø Pettersen (link) that discusses in detail how client-side JavaScript can be used to click a (hidden) button. That's the essence of the idea: some JavaScript code that checks the text field for changes, and when it observes any it activates a button. Brilliant and simple. I made some changes and improvements (hum!) to the code, and in the end I had only one chunk of JavaScript code and I had to set the name of the text field and the button.

Requirements

JSHeader

This code must be put into the JSHeader element of the form:

var text= "";
var state= 0;
var f;

function searchText() {
	if(!f)
		f= document.forms[0];
	switch(state) {
	case 0: // init
		if(f.Filter.value==text) 
			break;
		state= 1;
		text= f.Filter.value; 
		break;
	case 1: // text changed
		if(f.Filter.value!=text) {
			text= f.Filter.value; 
			break;
		}
		// no more changes recently
		f.FilterButton.click();
		state= 0;
		break;
	}
	setTimeout("searchText()", 600);
}

setTimeout("searchText()", 600);

Names

Then the text field and button should have names so the code can find them. In the code above I named them Filter and FilterButton. For the button, the name must be explicitly set as the HTML name, on the last tab of the Properties box.

What happens...

I wanted the code to trigger the button when there's a real change to the text, but not while I'm typing. So, it checks every 600 ms if the text has changed, and if so, if it hasn't changed again. While there are changes (meaning that the user is typing), nothing should happen. We found out that 600 ms is long enough for the average user to type more than one letter of a word, but also short enough to give the impression that the button is triggered immediately.

Is there room for improvement? Possibly, please let me know!

© 2020 Sjef Bosman · Consultant HCL Domino/Notes
SIRET 442 133 252 00019 · tel. +33 475 252 805
sjef@bosman.fr · sjef.bosman