views:

37

answers:

1

Hi,

How do I handle selection of multiple items with autocomplete? The objects I return from my JSON web service contain an ID and a Label - the ID is the ID of the entity in the database, and the Label is some text to display for the user.

At the moment, when I select an item in the autocomplete dropdown, the value of the item's ID is stored in a hidden field, and the label is displayed. When I remove the label, I clear the ID of the hidden field - this is done by adding an anchor element to the DOM that handles this.

Now, I want to have multiple selections. I want to be able to enter some text, get an autocomplete dropdown, select an item and some other options, then be able to click an 'Add New' button or the likes to be able to select another instance.

For example, I'd type in a person's name and get an autocomplete selection. I'd select a person, and then enter their age, and click 'Add'. The person's id, name, and age will be stored somewhere so that I can retrieve it on the server side when I post back.

I'm not quite sure how to do it? I'm thinking of a hidden field - I assume that many hidden fields of the same name/id turn up on the server side as an array, which I can then use. But I haven't tried this yet in ASP.NET.

How have you gone about this problem?

A: 

Well, no suggestions. I did it eventually by, in the autocomplete selection, creating a nicely styled span. It's text contains the label, it contains an anchor element that I bind a click event to that removes the element if necessary, and I use the jQuery data API to store the ID value on the span. This span gets added to a container div, before the textbox that I'm using to autocomplete. I also bind a keyup event to the textbox to check for backspace - when it's pressed and the textfield is empty, then I remove the last autocomplete item. It's a little more complex though, since by the time the keyup event is pressed, the character that was being removed from the textbox has already been removed, so I store the actual value in the keydown event too using the jQuery API and check this in the keyup event.

There is a hidden field on the form, that I keep populated with a comma-separated list of ID values extracted from the span's data. This can be kept in sync when adding/removing items, or only when I post back - it's simplest to just clear it and repopulate it, and is quite efficient as far as I can tell.

When loading the page, the spans and hidden field must be generated.

Hope this helps anyone else looking for a solution.

jamiebarrow