Thursday, April 17, 2008

Multiple Auto-complete for Woodstock (Netbeans Visaul Web Pack (VWP))

I have been searching around for multiple autocomplete but couldn't really find one that works seamlessly with Netbeans VWP. There is of course the work of Dimitry [http://blogs.sun.com/dmitry/entry/creating_autocomplete_entry_field_with] but this is limited to a single entry auto-complete (i need a multiple one). So just like any good hacker, I decided to see if I can improve Dimitry's code and come up with my own and le voila:

Basically, the flow of things are exactly like the one used by Dimitry, except that

1) When editing the textfield, not only that I refresh the listbox, but also see if the user is typing a comma, in which case, I will reset the filter in Page1. The filter will only contain words typed after the comma.



//in Page1 setFilter
int index = value.lastIndexOf(',');
if (index >= 0){
this.filter = value.substring(index+1);
}else{
this.filter = value;
}
listbox1DefaultOptions.filter(filter);



2) Also, the user could type the down arrow key while typing in the textfield, this will bring our focus to the listbox.

//in tf's OnKeyUp
var evtobj=event? event : window.event //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
var unicode=evtobj.charCode ? evtobj.charCode : evtobj.keyCode

if (unicode==40){
document.getElementById('form1:listbox1').getSelectElement().focus();
}
document.getElementById('form1:listbox1').refresh('form1:tf');



Just to complete things, the user could also type a comma while browsing the listbox, this will be detected in the OnKeyUp event of the listbox

//OnKeyUp of listbox1
var evtobj=event? event : window.event
var unicode=evtobj.charCode ? evtobj.charCode : evtobj.keyCode
var character=String.fromCharCode(unicode)
if (unicode==44){
var text = document.getElementById('form1:tf').getProps('value').value + ',';
document.getElementById('form1:tf').setProps( {value: text } );
document.getElementById('form1:tf').getInputElement().focus();
}else{
var text = document.getElementById('form1:tf').getProps('value').value + character;
document.getElementById('form1:tf').setProps( {value: text } );
}


Of course if the listbox change, we need to append the listbox selecte entry to the textfield. (Note that We will replace any entry that is after the last comma.)

//OnChange event of listbox
var text = document.getElementById('form1:tf').getProps('value').value;
var index = text.lastIndexOf(',');
if (index >=0){
var stext = text.substring(0,index+1)+document.getElementById('form1:listbox1').getSelectedValue();
document.getElementById('form1:tf').setProps({value: stext});
}else{
var stext = document.getElementById('form1:listbox1').getSelectedValue();
document.getElementById('form1:tf').setProps({value: stext});
}

No comments: