IT IS HERE! Get Smashing Node.JS on Amazon Kindle today!
Show Posts
← Back to homepage

TextboxList Autocompletion

Demo here

In my previous blogpost I explained how to extend TextboxList to add closing functionality via a link added to each box. But it was missing an important ingredient: autocompletion!

Again, all we have to do is extend the TextboxList class, override some methods, some events, and create some new ones (all prefixed by auto)

var FacebookList = new Class({

  Extends: TextboxList,

  data: [],

  options: {
    onInputFocus: function() { this.autoShow(); },
    onInputBlur: function(el) {
      el.value = '';
      this.autoHide();
    },
    onBoxDispose: function(item) {
      this.autoFeed(item.$attributes.$text);
    },
    autocomplete: {
      'opacity': 0.8,
      'maxresults': 10,
      'minchars': 1
    }
  },

  initialize: function(element, autoholder, options) {
    arguments.callee.parent(element, options);
		this.autoholder = $(autoholder).set('opacity', this.options.autocomplete.opacity);
		this.autoresults = this.autoholder.getElement('ul');
		var children = this.autoresults.getElements('li');
    children.each(function(el) { this.add(el.innerHTML); }, this);
  },

  autoShow: function(search) {
    this.autoholder.setStyle('display', 'block');
    this.autoholder.getElements('*').setStyle('display', 'none');
    if(! search || ! search.trim() || (! search.length || search.length < this.options.autocomplete.minchars ))
    {
      this.autoholder.getElement('.default').setStyle('display', 'block');
      this.resultsshown = false;
    } else {
      this.resultsshown = true;
      this.autoresults.setStyle('display', 'block').empty();
      this.data.filter(function(str) { return str ? str.test(search, 'i') : false; }).each(function(result, ti) {
        if(ti >= this.options.autocomplete.maxresults) return;
        var el = new Element('li').set('html', this.autoHighlight(result, search)).inject(this.autoresults);
        el.$attributes.$result = result;
        if(ti == 0) this.autoFocus(el);
      }, this);
    }
  },

  autoHighlight: function(html, highlight) {
    return html.replace(new RegExp(highlight, 'gi'), function(match) {
      return '' + match + '';
    });
  },

  autoHide: function() {
    this.resultsshown = false;
    this.autoholder.setStyle('display', 'none');
  },

  autoFocus: function(el) {
    if(! el) return;
    if(this.autocurrent) this.autocurrent.removeClass('auto-focus');
    this.autocurrent = el.addClass('auto-focus');
  },

  autoMove: function(direction) {
    if(!this.resultsshown) return;
    this.autoFocus(this.autocurrent['get' + (direction == 'up' ? 'Previous' : 'Next')]());
  },

  autoFeed: function(text) {
    if(this.data.indexOf(text) == -1)
      this.data.push(text);
  },

  autoAdd: function(el) {
    if(!el || ! el.$attributes.$result) return;
    this.add(el.$attributes.$result);
    delete this.data[this.data.indexOf(el.$attributes.$result)];
    this.autoHide();
    this.current.$attributes.$input.value = '';
  },

  createInput: function(options) {
    var li = arguments.callee.parent(options);
    var input = li.$attributes.$input;
    input.addEvents({
      'keydown': function(e) {
        e = new Event(e);
        this.dosearch = false;
        switch(e.code) {
          case Event.Keys.up: return this.autoMove('up');
          case Event.Keys.down: return this.autoMove('down');
          case Event.Keys.enter:
            this.autoAdd(this.autocurrent);
            this.autocurrent = false;
            this.autoenter = true;
            break;
          default: this.dosearch = true;
        }
      }.bind(this),
      'keyup': function() {
        if(this.dosearch) this.autoShow(input.value);
      }.bind(this)
    });
    input.addEvent(Browser.Engine.trident ? 'keydown' : 'keypress', function(e) {
      if(this.autoenter) new Event(e).stop();
      this.autoenter = false;
    }.bind(this));
    return li;
  },

  createBox: function(text, options) {
    var li = arguments.callee.parent(text, options);
    li.addEvents({
      'mouseenter': function() { this.addClass('bit-hover') },
      'mouseleave': function() { this.removeClass('bit-hover') }
    });
    li.adopt(new Element('a', {
      'href': '#',
      'class': 'closebutton',
      'events': {
        'click': function(e) {
          new Event(e).stop();
          if(! this.current) this.focus(this.maininput);
          this.dispose(li);
        }.bind(this)
      }
    }));
    li.$attributes.$text = text;
    return li;
  }

});

window.addEvent('domready', function() {
  // init
  var tlist2 = new FacebookList('facebook-demo', 'facebook-auto');

  // fetch and feed
  new Request.JSON({'url': 'json.html', 'onComplete': function(j) {
    j.each(tlist2.autoFeed, tlist2);
  }}).send();
});

It works by caching all the results from a JSON Request and feeding them to the autocompleter object. When a item is added as a box, it’ removed from the feed array, and when the box is disposed it’s added back, so that it becomes available in the list when the user types.

Another new feature is that you’ll be able to let it add boxes from the HTML directly:



Type the name of an argentine writer you like
  • Jorge Luis Borges
  • Julio Cortazar

The constructor now takes new parameters to configure the autocompletion, like the minimum number of characters to trigger the dropdown, and more.

Changelog

  • 0.1: initial release
  • 0.2: added click support, removed $attributes use, code cleanup

Download

Click here to download the zip with code and examples

325 Comments

David said

This is brilliant.

Very slick and it seems to just work like you’d expect… Very neat, this definately has lots of potential.

Ahmed said

thanks for such cool thing!

Jacob said

Of course the next step is to allow AJAX submissions for items not in the autocomplete list (on enter key).

Looks awesome!

Nuri Akman said

Very useful and smart autocompletion! Simple to implement !

But, How can I catch selected items after submitting form?

Guillermo Rauch said

@Nuri
Call the update function when you submit your form.

Very nice, I almost included it in my project away.

But it doesn’t seem to work when you click on one of the names in the drop down list, only when you use press enter. (Firefox 2.11, Windows XP)

Is this on purpose or something that was overlooked?

Guillermo Rauch said

@James
It actually took me longer to post the update than to code it itself… I’ve just uploaded it for you to use it in your project !

Ali Pour Zahmatkesh said

its very nice components with mooTools!
nice and very nice;)

Nick said

Very nice – exactly what I’ve been looking for

I am trying to use this with an ajax response (so names are pulled in from db – any tips on how to do this would be a great help.

Thanks again

Nick

Guillermo Rauch said

@Nick
This already works with an ajax -ajaj really, the last j being of json- response

Nick Light said

Yeh I thought it would – but can’t seem to get the autocomplete to list the items in the json.html file….. only the two listed initially

“Jorge Luis Borges
Julio Cortazar”

Thanks

Nick

HiTMaN said

This tool is GREAT!!!

I’m using it in my site, excellent stuff. thank you very much

[note] for other who’s going to use this, there’s a bug with the mootools function .removeClass(‘classname’) ; which doesn’t work in IE7 as far as i know.
simply change to .className = ”;

i’m still trying to figure out how i can set some of this options, only if there were example.

sdor said

I’m having the same problem as “Nick” (two posts above). I can’t get the json file to load. Everything looks same as site example. Just to be safe, I copied site JS and replaced in my JS file to no relief. Any thoughts?

Thanks.

p.s. Very cool. Just need it to work for me :-)

Guillermo Rauch said

Guys: if json.html doesn’t work for you, change the url to something that does. Remember it’s only intended as an example.

Renjith said

Very Nice One..
I integrated it with PHP
The auto sujjest is working..
But i hav a doubt
how to submit the data??
sujjested result it is not in the text box

Guillermo Rauch said

@Renjith
Use the .update() method of your TextboxList instance when submitting the form.

Ignacio said

Che, buenísimo esto, yo tambien soy de Argentina, me parece que acá esta el talento!

Zach said

Still cant get the update to fire. New to javascript

Ninja said

Had to create the instance outside the addEvent

var tlist2 = MsgFriendsList;

window.addEvent(‘domready’, function() {
// init
tlist2 = new MsgFriendsList(‘MESSAGEToUser’, ‘MsgFriends-auto’);

Changed the the update function to update a hidden input

update: function() {
$(‘MESSAGEToNames’) = this.bits.getValues().join(this.options.separator);
//this.element.set(‘value’, this.bits.getValues().join(this.options.separator));
// return this.bits.getValues().join(this.options.separator);
},

and then just called the tlist2.Update() in my forms onsubmit

I might of been wrong to do it this way, but it works

Ninja said

Missed out a .value after the $(’MESSAGEToNames’)

Now it works

Ignacio said

I’m looking this script for only Autocompletion, without the multiple select. But no other, I want THIS script. Any help? Thanks! I’m desperate!

Guillermo Rauch said

@Ignacio
It’s not worth using this script only for autocompletion.

Ignacio said

Thats ok, but the idea is use both, with a true or false, with multiple selects and without, you know what I mean

Guillermo Rauch said

@Ignacio
In that case, a good idea would be to add an option to limit the number of boxes you can add. I’ll probably add it soon

Ignacio said

Thanks

Nick said

hello

I have changed the url many limes in test.js – - i keep getting the same error “j has no properties
[Break on this error] j.each(tlist2.autoFeed, tlist2);”

Please help

EGBlue said

Nick, I’m having the exact same problem. it occurs because it cannot seems to open json.html, so it cannot iterate through the values. I’m not proficient with Mootools so i don’t really know how things work over there, i’m a Prototypejs guy. I was hoping somebody who is more knowledgeable with Mootools could elaborate more.
Thanks
– EGBlue

Wicked. Have been looking for something like this. Saving it to my delicious right now!

nicefella said

hi,

this is very cool. but it didn’t work for me either although i simply uploaded the sample code to one of my hosting directories.
it doesn’t seem to fetch the items from json.html.
all i get are:
“Jorge Luis Borges
Julio Cortazar”

is this a hosting-related problem?
does this application require any other software to be installed before?

any help?
thanks.

nicefella said

@nicefella

ok. i fixed the problem by changing the name of json.html with json.asp and test.html with test.asp

now,

can s.o describe how i am going to use this “update” function to catch the items selected in the textboxlist.?

Ozkan said

I first tried the original code itself and then Ninja’s method, but, no luck.. I can’t get the values.. Any ideas..?

P.S: I am using ASP.NET & C#

xavo said

In ie7 it’s a error.

When you put 2 letters in a text see the next error:

The objecto not accept de property ot method.

Thank u and excuse my poor english.

EGBlue said

I was able to get it working simply by renaming the file from json.html to json.php, similar to nicefella’s method. Make sure you put it on your server or localhost. My suggestion is, since it acts like a dropdown select, in the JSON to have Title, and Value. they don’t have to be the same. So when clicked .update() you get the values, while the Titles are those that being displayed on the actual list.

Ozkan said

@EGBlue, can you send me the working sample code?
ozkana {at] gmail (dot} com

EGBlue said

@Guillermo Rauch
Do you mind if i’ll start on the process of translating your code into Prototype?
Since Prototype is not compatible with Mootools, I cannot use your script, I really like it though and already have ‘pimped’ it.
I would like to know if I can translate it into Prototype, commenting that it is based on your script of course.
Thanks
– EGBlue

sapporo said

@EGBlue

If you have successfully translated the nice guillermo code into prototype, you re welcome

thanks

sapporro (at] gmail (dot] com

danny said

very nice autocomplete.

how can i get more than one autocomlete field on a single page to work? i cant get it.
thx

EGBlue said

Hey guys, for those who are interested. A ported version of this great script into PrototypeJS can be found at http://www.interiders.com

flipthefrog said

When running it locally, i get this error on test.js, line 170

j has no properties

running it on apache works

Marcel said

Pretty slick… it’s missing some of the features of the Facebook control, though:
- When you hit the up and down arrows in your, you’re not canceling the event, so your cursor moves around in the text box
- Facebook’s searching is done with a binary search, you’re using a sequential search… you may notice some slow down after like 5000 elements
- Facebook’s version will give you a scrollbar if more than 10 results come back. You can even hit the down arrow with nothing typed in, and it will give you the whole list. The results are rendered on a timeout so it remains quick and responsive even when enumerating thousands of results.

I’m impressed, though!

Guillermo Rauch said

@Marcel
Really interesting suggestions.. I guess I’ll have to release a new version then !
Thanks

Devalnor said

Hi,

I like your code style : var that = this;

;-)

Anyway thanks for this. It’s a very nice one. I’ll adapted it to accept new values with other css classname for them.

I’ll keep you in touch.

Devalnor

EGBlue said

@Marcel
Nice suggestions. How exactly can you employ Binary Search though in that kind of script?
Let’s say you sort it by first name, and using Binary Search you are able to find the first name. Then you use that index to start a sequential search from that point on? Assuming you figure that out, how do you then use it for Last name?
Obviously such a solution would be great, i’m just not sure how it can be employ.
Thanks in advanced.

fedi said

very nice script.

However, I am trying to insert the selected options into the DB and can’t get it work. What do I need to do?

working with php/mysql

thanks in advance

Brian said

I still can’t figure out how to pull values using the update function.

I set the onsubmit=”tlist2.update()” for a button in my form, but it doesn’t do anything. It seems to be something simple that I’m missing. Could anybody please shed some light?

The autocomplete is a very wonderful tool. However, the problem is adding a value that does not exist in the autocomplete list to the input box. if for example Im using it for a intramail whereby users can send mails to each other within a site and the autocomplete lists out users who are already in the member’s friend list, what happens if he also wants to send to a member who is not in his friend’s list? I was thinnking thst typing in the value and pressing enter will do the trick but it doesnt. Tested on IE7 and Opera9

Bobby said

I have the same issue like Brian. However, it seems there is no support or advice here. If someone of you knows the answer could you please help us. I believe many people here have the same problem.

ian said

i tired using the update function, it works for default values, but after trying to input something, list2.bits gets whatever was in the autocomplete list, instead of what is in the textboxlist. Any solution?

ian said

nevermind i got update to work.

Jan said

Does anyone have an example of how to use update function (new to java…). Any example will do, I’m sure I can figure it out, just don’t know where to start on this one.
Thanks!

Jan said

Hey All,
Love the script. Yet, I have a problem. I am new to Java and I have no idea how to ‘call the update()’ function, does anyone have an example of how this is done? Sure I can figure it out if I just can see how it’s done.

Thanks!

sanath said

Hi I am very much interested in this work . I am from a java background and we use DWR not JSON(and I am not familiar with JSON ). I need to understand this piece of code that I have pasted here.

new Request.JSON({‘url’: ‘json.html’, ‘onComplete’:

I have also downloaded the sample demo and found that it contained a file named “json.html’ which contained a string array. How can I integrate this with DWR? or else If I am going to use jason wuts the step that I need to take to integrate it with my code . CURRENTLY i AM GETTING THE DB DATA VIA DWR TO MY CLIENT SIDE AND I AM ABLE TO PRINT THE RELEVANT DATA USING “alerts”””

Martin said

Great script, I will for shure use it in my future projects.

Mark said

is there anyway to only allow only one name to be submitted, instead of an unlimited amount?

ulas said

i made my own list for autocomplete, but i want that box be empty at first – how can i ?

Fusion said

Hi. This is wonderful stuff. I’ve used this in one of my projects and has proved a great success. But like everything, it has some issues. Here’s what it is..
I’m updating the dropdown list, i.e. fetchfile on every keyword selection. e.g. If i search abc and get 10 results. I select one of them. Then i search again (type again). Now i’m making a new JSONString which returns say 2 results. But my drop down is showing 9 keywords options.
In short, the issue is i want to update the drop down list on every hit. The JSONString i’m returning is updated but the drop down list is not..
can the authors or anyone else please help me out on this.. Kinda urgent matter.
Many thanks.

NextMint said

Hi,
Could anybody post a working example of how to get the data posted? What needs to be changed, and where?

Many thanks

Korayem said

mega slick…loong live ASP.NET

Korayem said

Oppps..ditch that asp.net part in my comment, it was a stupid copy paste error….

Thanks for sharing, this is super cool

JP! said

Hello everyone!

Where do i put the update() function!? People say they figured it out but don’t post the solution!

JP! said

after several hours of fustration i figured it out ! (Using ninja’s method) but it was even easier. I left the update function as is!

// Like ninja said. Placing tlist2 outside the addEvent.
var tlist2 = BandsList;

window.addEvent(‘domready’, function() {

tlist2 = new BandsList(‘bands’, ‘bands-auto’);

// fetch and feed
new Request.JSON({‘url’: ‘json.php’, ‘onComplete’: function(j) {
j.each(tlist2.autoFeed, tlist2);
}}).send();
});

//// === in the HTML form ==== ///

JP! said

after several hours of fustration i figured it out ! (Using ninja’s method) but it was even easier. I left the update function as is!

// Like ninja said. Placing tlist2 outside the addEvent.
var tlist2 = BandsList;

window.addEvent(‘domready’, function() {

tlist2 = new BandsList(‘bands’, ‘bands-auto’);

// fetch and feed
new Request.JSON({‘url’: ‘json.php’, ‘onComplete’: function(j) {
j.each(tlist2.autoFeed, tlist2);
}}).send();
});

//// === in the HTML form ==== ///
<input type=”submit” onClick=”javascript:tlist2.update();” value=”Submit” />

Will said

I’m with JP. I’m not sure where to put the update function. So if someone could explain it that would great!

Thanks.

Delapouite said

Here is an example code to put in the domready :

window.addEvent(‘domready’, function() {

var tlist2 = new FacebookList(‘facebook-demo’, ‘facebook-auto’);

// fetch and feed
new Request.JSON({‘url’: ‘json.html’, ‘onComplete’: function(j) {
j.each(tlist2.autoFeed, tlist2);
}}).send();

$(‘facebook-form’).addEvent(‘submit’, function(){ //facebook-form is the form id
tlist2.update();
})
});

One problem remaining on IE :
pressing enter while the autocomplete list opened submit the form instead of just adding the list item like the Fx / Opera behavior

Pablo Rey said

loco, no se cuanto sabes de ajax… pero me parece que de literatura argentina sabes bastante ;)

Pablo Rey said

nice and usefull ;)

Sean O said

Very Cool. Any jQuery implementation of this, or something similar?

Craig said

Excellent work by the way. Love it. Ive noticed though that it isnt populating any kind of hidden fields so that you can POST the information with a submit button? Is this something you are looking to add?

Guillermo Rauch said

@Craig
The update() method takes care of that. You can either call it yourself or add it to the blur() method, which is what the upcoming version does (since so many people asked).
Nice website, by the way.

Great idea to improve the feedback for the user. Beside that thank you the possibility to get the source coude for free ;)

Ralph

fedmich said

Thanks for the script :)

Rainmore said

That’s a great script. Thanks!!

Well, I met a problem here that I can’t input any other name but only the name from file.

How can I submit the name from either the list file or from the input by myself?

Thanks for the help.

Rainmore

Rainmore said

After going through all the notes, I summary some Q&A hereAfter going through all the notes, I summary some Q&A here:
Q:The script doesn’t work on dropdown list? Or No dropdown list ?
A: Please change the following file name to .php, .asp or .jsp rather than .html
Eg:
json.html ->json.php
test.html -> test.php

Q: Can’t upload the list?
A: 2 steps
1. Modify test.php (if you had change the extension of test.html) or test.html
a. Add name and id to the form as “facebook-form”;

b. Add name to the input where id = “facebook-demo”;

c. Add submit button within the form

2. Add a script to the file test.js at line 172 or add the script within the funciton window.addEvent(‘domread’,function()) as
$(‘facebook-form’).addEvent(‘submit’,function(){ // facebook-form is the form id
tlist2.update();
})
After the change the function should be:

window.addEvent(‘domready’, function() {
// init
var tlist2 = new FacebookList(‘facebook-demo’, ‘facebook-auto’);

// fetch and feed
new Request.JSON({‘url’: ‘namelist.php’, ‘onComplete’: function(j) {
j.each(tlist2.autoFeed, tlist2);
}}).send();

$(‘facebook-form’).addEvent(‘submit’,function(){ // facebook-form is the form id
tlist2.update();
})
});

HTH!!!!

antonio said

For the next version it would be great if you could use a json file that has IDs associated with values, like: ["32":Sylvia Molloy","12":"Julio Cortazar".....] And store just the IDs in the input element. That would be VERY useful if you need to get the ID of the selected objects when you process the form.

Alan said

Will there be a version with Keyboard Support?

Jeff Liu said

Great Job!
What is this license?

Jeff Liu said

Hello everyone
Is there an article only on this cute auto-complete ?
since i don’t need the TextboxList

I donwload the code and i have a problem with test.js
Just change one line of code

j.each(tlist2.autoFeed, tlist2);
chacnge to
var j = j.each(tlist2.autoFeed, tlist2);

Imran said

Hey this is really cool thanks, I will use this :)

is it possible to link this to a access db with VB script does any one know?

ryan said

i tried this using mootools 1.2 (non-beta) but it wasn’t working. what seems to be the problem?

Hannes said

Hey,

I’m also interested in getting this thing to work with moo 1.2!
Any plans for a soon 0.3 ?

PLxKARL said

I know….compatible version for 1.2 would be very nice. I LIKE !!!

Dan said

Hey, great script, only trouble is that I need it to work alongside another, lightbox script actually which itself requires more than mootools-beta-1.2b1 offers.

Is there anyway I can get this to work with mootools-1.2-more.js for example?

Dan said

Sorry, my mistake, it doesnt require the more mootools version….just mootools-1.2-core-yc.js instead. So how can I get both:

mootools-1.2-core-yc.js

and

mootools-beta-1.2b1.js

working in the same script?

    gerrard8dg said

    hey dude, its the same problem im facing now.. did u manage to solve it? any help is appreciated.. cheers!

Daniel said

Trying to convert this to v1.11 and I’m soo close! Wondering if anyone can have a look at it for me: http://mavrickdesign.com/test.html

T.Mailrajan said

Hi,
This is wonderful.

but the page is loading with content.If i want without cont ,what will i do?
sorry for poor English.

Rex said

Hey this is a nice implementation. We built a very similar thing with scriptaculous, just came across your implementation with mootools.

http://devblog.rorcraft.com/2008/8/13/the-facebook-autocomplete-address-to-field

Justin said

Will this work with v1.2? It hasn’t for me. Also, will there be limits feature on how many can be added in one textarea? How about for input that isn’t in the json file?

drag said

your demo doesn’t work in IE7

this does not fill me with confidence

Joe said

IE 7 seems to give me an error when matching the second letter typed…

it gives this error “object doesnt support this property or method”

If u dont type a second letter, it all works as expected.. yet if u do, it no longer functions..

any ideas??

Ben said

Hey Guillermo, awesome script you wrote here! It’s really amazing!

Any chance you can port this to jQuery? The auto-complete plugin that jQuery has pretty much sucks!

Alex H said

I absolutely love this script. I am running it with MooTools 1.2 (release) but it comes up with this error : “arguments.callee.parent is not a function”

Does anyone have an idea how we get around this? It only seems to work with MooTools 1.2 Beta and not release.

Am i missing something?
Alex

ADX said

Great job. Looks really great.
Would be great if you do a port to jQuery framework. Thanks.

Gordon said

This is really awesome! Thank you for creating this and making it available! I just had one idea that I think would be cool to see implemented, and probably wouldn’t be all that difficult of a change:

Currently it selects the data into the blue boxes when you press enter, but you could allow this to take place with different keystrokes as well. For instance, typing a comma could automatically select the current item and move onto the next.

Just a thought, and thanks again!

Chloe said

The Request.JSON just doesn’t work for some reason in Firefox 3. It will give a “syntax error” in the error console, and say ‘j’ not defined. It seems to have trouble when the request is made to the local file system. To make it work, just insert the array of options into your script somehow, with an include() perhaps, or with a generic XMLHttpRequest and eval() the results.

test.js, line 164:

window.addEvent(‘domready’, function() {
// init
var tlist2 = new FacebookList(‘facebook-demo’, ‘facebook-auto’);

// fetch and feed
var jsonArray = ["Jelly Fish", "Sylvia Molloy", "Manuel Mujica Lainez", "Gustavo Nielsen", "Silvina Ocampo", "Victoria Ocampo", "Hector German Oesterheld", "Olga Orozco", "Juan L. Ortiz", "Alicia Partnoy", "Roberto Payro", "Ricardo Piglia", "Felipe Pigna", "Alejandra Pizarnik", "Antonio Porchia", "Juan Carlos Portantiero", "Manuel Puig", "Andres Rivera", "Mario Rodriguez Cobos", "Arturo Andres Roig", "Ricardo Rojas"];
jsonArray.each(tlist2.autoFeed, tlist2);
// new Request.JSON(
// {
// ‘url’: ‘json.js’,
// ‘secure’: false,
// ‘onComplete’: function(j, text) {
// alert(text);
// j.each(tlist2.autoFeed, tlist2);
// }
// }
// ).send();

});

Chloe said

The reason the form submit was not passing the value was because the form input element needs a name, for without it it won’t be included.

In test.html, line 29, add a name to the input:

On line 20, add an onSubmit event to update the list:

In test.js, define the tlist2 variable outside of the scope of the anonymous function at the bottom:

var tlist2;
window.addEvent(‘domready’, function() {
// init
tlist2 = new FacebookList(‘facebook-demo’, ‘facebook-auto’);

Then when you submit, your form post URL will look like:

test_submit?testinput=hello&autocompleteinput=Jelly+Fish

Chloe said

To make this list only accept one item, make the following changes:

test.js, line 106, autoAdd:
input.set(‘value’, ”);//.focus();
if (this.data.length>=1) {
input.style.visibility = ‘hidden’;
input.style.display = ‘none’;
}

line 160, or 164 after the previous insert:
},

dispose: function(el) {
var li = arguments.callee.parent(el);
var input = this.lastinput || this.current.retrieve(‘input’);
input.set(‘value’, ”).focus();
input.style.visibility = ‘visible’;
input.style.display = ‘block’;
}

This will hide the input box to prevent further entries after one item has been added. It is probably fairly simple to make the # of items configurable, perhaps with TextboxList.count, but I’ll leave that to others.

    sammy said

    Is there a way to post (submit) right after the selection has been made?

Chloe said

How do you add multiple lists on the same page? I noticed that when you instantiate it, you pass the id of the input box and the id of the div tag.

tlist2 = new FacebookList(‘facebook-demo’, ‘facebook-auto’);
tlist3 = new FacebookList(‘facebook-demo2′, ‘facebook-auto’);

The only problem is, when the autocomplete list pops up for the 2nd list, it pops up under the 1st list! Changing the div id tag name doesn’t help, because THEN the popup list is not formatted. The test.css has styles for facebook-auto and if you rename the div tag, then the inner elements (popup list) aren’t formatted.

The only solution I can think of is inline styles for all the popup elements, which could get messy. Any other solution?

itsik said

fix for 1.2:

replace all the:
arguments.callee.parent

with: this.parent

on test.js

itsik said

more fixs for 1.2:

on textboxlist.compressed.js

replace:
this.bits.remove

width:
this.bits.erase

replace:
this.events.remove

with:
this.events.erase

joe said

does anyone have a solution for the problem in IE?

i keep getting the error “Object doesn’t support this property or method”

any help is greatly appreciated!

joe said

sorry, to clarify a bit more…the error occurs when you attempt to type in a second character in the text box. this leads me to believe the problem is with the following line in test.js

if(this.autocurrent) this.autocurrent.removeClass(‘auto-focus’);

thanks again.

joe

SanNhac said

Very Nice, thank you very much

Chloe said

I’ve given up on this for auto-complete functionality. I recommend the Yahoo AJAX library, which is FAR more robust and configurable, with much more user support and documentation provided.

developer.yahoo.com/yui/autocomplete

zyxel said

how about a facebook footer navigation??? any example for it??

kohaci said

That’s so cool.

L3tos said

If list more than specific number, can it be set to be scroll down, so list is not too long ??

yeahcmoi said

How work the other parts of facebook, like adding a comment ?

Gracias por el codigo exelente

Saludos
—————————————-
http://www.joelcristobal.com

Rolando said

hi, There are some parameters to that match the first letters of autocomplete?. thanks

Dheeraj said

Hi,

The script is returning an error if there are more items in fetched.aspx file. There are around 5000 items in JSON format. This error is being fired in Internet Explorer 7.0. It worked well in Chrome.

Error: Stop Running this script?

A script on this page is causing Internet Explorer to run slowly. If it continues to run, your computer may become unresponsive.

Thanks,
Dheeraj

Herschel Stone said

d76angt0b5341hx4

tamara said

Hi, nice script, too bad it doesn’t work for large database item. It crash if database more than 500 items

peter said

love the script – this is fantastic ..thank you!

Hank said

can someone please email the zip file of a working version of “TextboxList meets Autocompletion”

Sense my email is going in public, I’ll use one I rarely use…
Mail {@] hankweb {dot] com

Also, check out my site @ http://hankweb.com — I also have enabled AJAX IM at http://im.hankweb.com and social networking at http://my.hankweb.com

Hank said

As In… Gets Data From JSON Link And Uses It

Markus said

Great Script!.
I was looking for something like this in jQuery, but I didn’t find anything.

Thanks for sharing!

selva said

i need to fill Autocomplete TextBox dynamically while type a character inside that , the textbox is inside one Gridview cell… can anyone help me to resolve ?

mat said

Has anyone modified the script (or is there an update coming at all) that will allow JSON objects to be used instead of JSON array? I need to pass back a name value pair, displaying the name but storing the value for posting back to the server.

Thanks

metin said

@T.Mailrajan
@ulas

Just upload the files to a webserver to empty the input content… and rename json.html to json.php or .asp
after that, you can use all the json data in json.php and clean up the input …

Thanks to Guillermo Rauch for this script …

Hi.

Great script, like it alot!

But all the options are allready selected, I want to have a empty field and first when you select a “name” it will show up under the searchfield. Can anyone help me with this?

If do, please do send a mail to me ogkproduction @ gmail . com

    raki said

    Hi Christian
    I am looking for same thing , just wondering if you have found any solution please .

    If you manage to find one please let me know rikmon1 at gmail dot com

    Regards
    raki

    Milan said

    Hey guyes.

    I am looking for same thing , just wondering if you have found any solution please .

    If you manage to find one please let me know milan.andjelkovic@hotmail.com

    Regards

cevarief said

@ninja
Thanks for telling how to use update().

I prefer to use return this.bits.getValues().join(this.options.separator). So the textboxlist.js not bounded to hidden element ($(’MESSAGEToNames’)) unless we put it as function parameter.

Simply var data = vlist.update(); this will return text with separator defined.

@itsik
Thanks for the fix for Mootools 1.2. It works :D

    gerrard8dg said

    hey dude, could i please get the fix for mootools 1.2?
    i hope it addresses my problem.. cos i cant get the autocomplete to work with barackslides on the same index file. seems to be some conflict. thanks!

    Guillermo Rauch said

    Hey dude,

    There’s a big message at the top: http://cld.ly/6d1n1w

    This project has moved on beyond this post. Go to Projects > TextboxList.

cevarief said

Hi,

I have a question. i have 3 names picked from autocomplete. John, Audrey and Barret. I close Audrey. When i type A, the autocomplete doesn’t show Audrey anylonger. It seems that every name which has been picked and closed won’t display anymore in the autocomplete.

Instead of reupdate the json file, is there any function to recall what has been closed ?

Thanks before.

Zac said

Hello there–

When I submit the form, where does the information go? I can’t get it to input field data to post anywhere (using PHP and Javascript). I’d like to use this awesome autocomplete feature on a messaging system.

Zac said

I’m sorry I can’t spell. I meant to say:

I can’t get the input field data to post anywhere (using PHP or Javascript).

cem dulda said

Hello everyone,

i want use this, in my turkish project.
how can i use this with charset=”iso-8859-9″.

i changed all “utf-8″ to “iso-8859-9″ in test.html but im still seing bad characters.

Thanks before.

cem dulda said

Hello again,

i fixed the problem.
i saved as “json.asp” with encoding utf-8 and i changed all iso-8859-9 to utf-8 back in test.html =)

dario said

Vey good works but very breakable with mootools 1.2.

I was using your js with mootools 1.2 with the fix indicated but still with the fix there are some problems.

When do you think you’ll update your js for mootools 1.2?

regards, Dario

hamy said

To correctly post / get the data using update

Note: some of the code listed here is not correct – it has a syntax error causing it to fail.

Here is what you need to edit -

Your form needs to have an ID and a NAME. I chose files_form

Your input also needs and id and a name. I used files.

If you are not to familiar with JavaScript, then you will need to add a submit button to the form like this:

Note that there is no need for an onClick

Now open the file originally titled test.js
Do a search for tlist2

You will notice a line something like var tlist2 = new FacebookList(‘files’, ‘facebook-auto’);
That first parameter needs to be the ID/name of your input div

After you set that accordingly, place the cursor after the send();
Hit enter a few times to give yourself some room

Paste in this code
$(‘files_form’).addEvent(‘submit’, function () { tlist2.update(); } );

The $(…) needs to contain the ID/NAME of your form. Note that the line I just pasted ends in a semicolon. The previous examples left that out, resulting in a syntax error and their code not working correctly.

If you are planning on submitting large amounts of data, then perhaps you should use post instead of get, by changing form method=”post”

Your data will be stored using the ID/NAME of the input tag. In my case, I can access my data using
$data = $_POST['files']

The data is (by default) separated by ###. If you would like to change that, look for this in the textboxlist.js (or the compressed version): separator: ‘###’,

Hope that helps, and thanks for this awesome resource!

Hamy

    Edith said

    Million thanks, very useful information and it works perfectly. :)

hamy said

@myself

lol – by some of the code listed here – I mean some of the code listed above my post

;)

hamy said

@Guillermo,

One small change I would love to see if you decide to commit the time to an update -

Immediately after the first item is entered, jump the cursor up 50px or so. This would be to prevent the first item from being a different color from the second (because the first item is normally being hovered over, given that the user just clicked on the input)

Hamy

TechMind said

Hi,

I downloaded this code and when i execute the page i get javascript error

// fetch and feed
new Request.JSON({‘url’: ‘json.html’, ‘onComplete’: function(j) {
j.each(tlist2.autoFeed, tlist2);
}}).send();

So i am not able to run the code.. even the demo page URL given also gives thie error message..

Could you please help..

TechMind said

this is the error im am getting

j has no properties
[Break on this error] j.each(tlist2.autoFeed, tlist2);

Y.J. said

Nice component

Atish said

Hi!

Nice component, thanks. I have a small problem with it: How can I post values which are not in the autocomplete list?

Many thanks,
Atish

Christian said

I have tried to get a sql querry to work but I just cant make it work. Cant anyone who got it working please post a example .php file or text?

Ruben Ortiz said

Hello, i am testing in Windows Server 2003 and not working but in Debian Linux this work. Request config special?

Thank you, great script.

Eguino said

Great tool! Is it possible to connect it to a DB to take the values instead of the html? Thx

thomas said

How do to put nothing in input field at starting ?

    thomas said

    It pass ! sorry my question was untils

    raki said

    hi Thomas, i am facing same problem , please let me know how did you solved it

    Advance thanks
    raki

    sdfsdf said

    this is th tstin messag thi in th sn thirh owhorihwoihrowhorh oiwhroi

Logan said

There are some serious problems with this component: first and foremost, hitting Backspace will first select and highlight the previous tag (this is good), but hitting backspace again will (instead of removing the selected tag as expected), perform a browser Back command, leaving the page and potentially losing all the information entered into the form!

Secondly, you should really accept auto-complete entries with the Tab key. This is my expected way auto-complete should be performed.

    Guillermo Rauch said

    I hadn’t noticed the backspace bug, what browser are you testing on ?

    And tab for autocomplete is not a standard behavior for autocompleters, let alone a widget made up of various inputs like this.

    Edith said

    one day ago I had not noticed the backspace bug too, because my page (send new message) is opened in a new tab and thus the browser has no way to back to the previous page.

    after I sent a new message, the script back to the same page with a short sentence notifying the user that message has been sent. Here I re-use the page again by pressing enter in the address bar, now the page has chance to back to the previous page and the backspace bug can happen.

boon said

It’s really awesome script. I was really very much impressed with this code.

Is it possible to take the values from database instead of the html file…

    JasF said

    You can do it by retrieving from you database the data you need, creating a php variable for example in this form ["var1","var2",...,"varn"] and then writing that in a HTML file. PHP example:
    $fp=fopen(“json.html”,”w+”);
    $i=0;
    $contenido = “[“;
    while ($i<$veces){
    $nombre = $listaMiembros[$i]['nombre'];
    $contenido .= “\”$nombre”;
    $apellido = $listaMiembros[$i]['apellido'];
    $contenido .= ” $apellido”;
    $id = $listaMiembros[$i]['id_miembro'];
    $contenido .= ” $id\””;
    if ($i != $veces -1 ){
    $contenido .= “, “;
    }
    $i++;
    }
    $contenido .= “]”;
    fwrite($fp,$contenido);

tingon said

Hi…
Great script, but i gone crazy…..
I need to place automatically the cursor inside the text field when u open page….
anyone know the way to do this?
tnx

    Sridhar said

    Inside Body Tag, onLoad event make your cursor to point to your textfield.

iie sumitra said

wow….great job, thanks a lot,

mantap abissss…….top markotop……….

MissedGurl said

to make it compatible whit mootools 1.2, some change required
see http://forum.free.fr/autocomplete/

    xs_is said

    backspace doesn’t work with mootools 1.2.3.

What you are trying to accomplish would be possible with 2 auto complete boxes… Think about it. If you are making calls to your database script to pull out some data, there is no other way to tell the script to change sql flags and pull something else while typing in the same box.

    Guillermo Rauch said

    I don’t understand

    bert said

    good

shellmark said

Great script,

Is there a sample to put 2 input controls in one page, but the drop down values are different?

stephan said

Hey, is there a possibility to just allow the objects in the json array to be intyped (and maybe email-addresses)?

Great work but I can’t get it work with mootools 1.2

Babalaba said

Hi, could someone help to add top image-base imaged pointer to the drop-down menu like Mootool Autosuggest has.
http://www.alainalemany.com/wp-content/uploads/2008/09/autosuggest2.jpg

Dava said

How can I get the Values from that textbox?

wh0750 said

dsfsdfs67877 test test

marc said

Hi there!

i want to add the TypeWatch, a plugin that monitors the time between key strokes in a text input box with the textboxlist plugin.

Any idea how to do it?

    rob said

    How in the world do you get this working with mysql????
    want it to pull data from database not JSON.HTML

    please help!!!!

      Renevdkooi said

      Rob, you would create a php file which grabs the data from mysql and then output it as json, then you point the script to the php script which generates a json string. make sure the header is set correct, json is a bit picky with this

Steven Barnett said

So I have a database with about 8,000 entries (minimum, this is subject to grow). Naturally I don’t want to have a PHP file read the entire contents of the database and send back all 8,000 items to be cached and used in the auto-suggest. That’s just ridiculous. Rather, I’d prefer to select only those entries which begin with whatever the user has already typed (so if you type “aut”, it will turn up things like “automobile”, “automatic”, “autism”, etc)

I could do this if instead of sending the data to json.html it were sent to json.php?tag=aut, however I don’t know how to get the content of the input box while it’s still being edited. Help would be appreciated.

Увлекательно. Некоторые моменты не знал.

name said

:-(,

Tom and jerry said

no good because have only one text , i want multi text ?
var tlist1 = new FacebookList(‘userlist1′, ‘user-auto’);
var tlist2 = new FacebookList(‘userlist2′, ‘user-auto’);….
only one Request.JOIN …. I see not ok

Jasen said

I have a problem.
This scripts work fine in my case.
But, I was wondering. I just need ONE entry(with autocompletion, of course), and not the hability to select a lot of inputs.. .. how can I do it?
Andy idea?

Milan said

If someone has resolvde how to get the box empty and not auto with all this stuff you write in, msg me pls ! I will pay for resolve this problem!

Milan said

If someone has resolvde how to get the box empty and not auto with all this stuff you write in, msg me pls ! I will pay for resolve this problem! Mail @ milan.andjelkovic@hotmail.com

Duby said

You plugin seems pretty sweet, but the test in the download isn’t working. Its throwing a JS error of “j is undefined” from line 170 of test.js It won’t do any auto-complete functionality unless you delete the predefined values and search specifically for them.

tatil said

thankl you very good.

Ben said

Looks great, but I cannot get it to work. I am trying to use the jquery version with autocomplete and am having an issue. When I type a few characters in the input field and then click on one of the matches, I get a bug in Firebug that says “m is undefined”. And no selection appears up in my input field. Any ideas as to what might be happening? It feels like I may have initialized the plug-in incorrectly, but I can’t see what’s wrong.

Chris Morris said

I like how you have the floating clouds on this page…how did you do that?

Jamie said

I was looking for an autosuggest style dropdown that could be used in two scenarios: first, for a search box like Google Suggest/Facebook search/OS X Spotlight search; second, for a taglist-style box accepting multiple values. Textboxlist seems a good solution, but I’ve come across a few problems in TextboxList.Autocomplete.js:

1. When a function was given in options.remote.extraParams, the line data[this.options.remote.param] = search; stopped working (‘data undefined’).

2. In search() I had to change
if(this.values.length) this.showResults(search);
to
if(this.values) {if(this.values.length) this.showResults(search);}
to prevent ‘this.values is null’ error when deleting characters from a search phrase to make the currently displayed search results invalid.

3. Instead of search() being called directly on keypress events, I modified the code to run an intermediate method that only runs search() after a delay, to prevent too many requests to the server for remote requests.

searchTimeout:false,
searchIfRightTime: function(bit)
{
if(this.searchTimeout) clearTimeout(this.searchTimeout);
this.searchTimeout = setTimeout(function(){this.search();}.bind(this), 250);
},

PS The ‘LOAD PRIOR 50 COMMENTS’ link on this page doesn’t appear to be working (Safari 4)

Jon said

Hi, I am considering paying to this on one of my clients sites but i need it to work in Swedish. Anyone who knows how to add suport for letters: “å”, “ä”, “ö”?

rathinS said

Good Demo!!!

Jeisson Delgado said

Quisiera saber si se necesita alguna configuracion especial para que funcione en un servidor LINUX, gracias por cualquier ayuda.

jonhy87 said

como te jodio el flaco que te copio el plugin!!!

arfan said

can u tell me how i can get the selected value in php to insert into database of user selection.
because the field name is not working for me.
When i add a Submit button and try to get Date ($_GET/$_POST) empty string i find.
Can u help me. thanks

zsdds said

mensaje xx

Ade Abadi said

nice, love it

Bk082008 said

hello, I am trying to find a script that mimics the
facebook autocomplete/drag and drop form. I
think this tool is as close as I am going to get; it
looks very simular.

I want to use my MS-SQL database to call up
keywords. I also need it to work with my ASP
pages. Would be great if my users could also
drag and order the items (like on facebook).

Please share your knowledge with me regarding
my concerns.

Thanks

Sss said

zzz

Cyngus106 said

has anyone been able to get the spinner loading graphic to work?

    yes… just use $(‘YourWindowNameHere’).retrieve(‘instance’).showSpinner();

    Your’re wellcome

cjeys said

Hi! I’ve encountered some serious problems running this script together with prototype.js.
Any suggestions or ideas how to solve the problem?
Thanks!

cjeys said

Hi! I’ve encountered some serious problems running this script together with prototype.js.
Any suggestions or ideas how to solve the problem?
Thanks!

dassadsd said

man this is perfect

David said

I need to replace json.html such that it will generate json based on the input text. any ideas/suggestions?

Todor Panayotov said

Hello , 
I need a real time form maker that can be used from a client. 
Can you give me some information would be posible to buy a solution in this area.
Do you know something like this? Only to be custamized.

Can you geve me feedback on todor@wizzard:twitter .bg 

Thank you in advance. 

Ichweisnit said

Nice greez from Germany :) perfect script but only one important question:
Where are the value from the textfield? or who can i get the value i like to send the value from the textfeld with get in the url to the next page pleas help…

Cool plugin! Is there a possibility to also add some new tags and to commit they to server?

Tolgay007 said

How can i get value from text ?

dendy said

http://devthought.com/wp-content/articles/autocompletelist/json.htmlFailed to load resource: the server responded with a status of 405 (Not Allowed)
test.js:170Uncaught TypeError: Cannot call method ‘each’ of undefined

Graham Thomas said

Incredible work, thanks for this!

santhosh said

hi, this works fine in all browsers except IE9, can anyone tell me the solution to works in IE9

sparklets said

where are you giving the data please? I want to give js data from my C# code

Ola Apata said

Great effort! Looks great.
I tried using it for facebook friends autocomplete dropdown but i was just hiting too many obstacles i ended up using Yahoo YUI autocomplete control, along with facebook opengraph api i got this to work fine. It also has a submit button.

check it out here
http://fb-520.com/articles/facebook-friends-autocomplete-dropdown-selector

johnramirez said

To prevent the Backspace bug use this code in your :

document.onkeydown = function () {
var e = event || window.event;
var keyASCII = parseInt(e.keyCode, 10);
var src = e.srcElement;
var tag = src.tagName.toUpperCase();
if(keyASCII == 13) {
return false;
}
if(keyASCII == 8) {
if(src.readOnly || src.disabled || (tag != “INPUT” && tag != “TEXTAREA”)) {
return false;
}
if(src.type) {
var type = (“” + src.type).toUpperCase();
return type != “CHECKBOX” && type != “RADIO” && type != “BUTTON”;
}
}
return true;
}

Your thoughts?

About Guillermo Rauch:

CTO and co-founder of LearnBoost / Cloudup (acquired by Automattic in 2013). Argentine living in SF.