Autocomplete with strict key=>value pair with Scriptaculous (Part I)

I am using Scriptaculous for Autocomplete control, but in the example provided there is no way to select strict value.

Let me explain what I mean: Go to autocomplete example and try to select an entry in first group of fields. Well everything looking fine.
Then try to modify the entry, for example remove the last char from the field. and press somewhere on the web page /with the mouse/. Well as you can see this didn’t clear the value from ID field and in the real example, when the ID field is hidden, users could have wrong impression that the field is selected, they change it, but their change is not applied … and the complication occur.

In the second example, if you select the wrong value /change the selection for example to remove the last char/, the ID, when press with mouse somewhere outside all related fields get cleared.

Ok, how I did this:
In addition of all Scriptaculous code I add Event.observe from Prototype. This is the current implementation:

Event.observe("autocomplete", "blur", function (event){
                            var element = Event.element(event);
                            if($(element.id).value != $(element.id+'_check').value){
                                $(element.id).value = '';
                                $(element.id+'_id').value = '';
                                $(element.id+'_check').value = '';
                            }
                        }
                    );

Function explanation:
I have 2 additional fields – one for ID and another one for checking the entry selected.
So, on blur the script checking if the value in autocomplete field is the same as in autocomplete_check field. If they are not equal, then I clear all values simulating that entry selected is not in the list.

Of course there are variations of this action, it’s possible to add alert informing the user that the entry selected is not valid. Also it’s possible instead of clear the fields, to fill the autocomplete field with the value from autocomplete_check – this I am leaving to you.

This code was tested on Ubuntu and working correct on Firefox, Opera and Internet Explorer. Please inform me if there are problems in other browsers/platforms.

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

Leave a Reply

Your email address will not be published. Required fields are marked *