Skip to content

Instantly share code, notes, and snippets.

@spg
Created March 5, 2014 20:07
Show Gist options
  • Save spg/9375514 to your computer and use it in GitHub Desktop.
Save spg/9375514 to your computer and use it in GitHub Desktop.
Chosen hack for typeahead
ChosenOptions chosenOptions = new ChosenOptions().setNoResultsText("No results");
final ChosenListBox chosenListBox = new ChosenListBox(false, chosenOptions);
chosenListBox.setWidth("300px");
chosenListBox.addAttachHandler(new AttachEvent.Handler() {
@Override
public void onAttachOrDetach(AttachEvent event) {
if (event.isAttached()) {
$("input", container).keyup(new Function() {
@Override
public boolean f(Event e) {
String input = $("input", container).val();
value = input;
List<String> results = find(input);
for (int i = 0; i < chosenListBox.getItemCount(); i++) {
chosenListBox.removeItem(i);
}
// chosenListBox.clear();
for (String result : results) {
chosenListBox.addItem(result);
}
chosenListBox.update();
return true;
}
});
}
}
});
chosenListBox.addUpdatedHandler(new UpdatedEvent.UpdatedHandler() {
@Override
public void onUpdated(UpdatedEvent event) {
$("input", container).val(value);
}
});
container.setWidget(chosenListBox);
private List<String> find(final String input) {
if (Strings.isNullOrEmpty(input)) {
return new ArrayList<>();
}
Logger logger = Logger.getLogger("input");
logger.info(input);
List<String> data = Lists.newArrayList("aaaa", "something", "blah", "blah2", "fja7s", "zzacja", "b", "s",
"salut", "lol");
return Lists.newArrayList(Iterables.filter(data, new Predicate<String>() {
@Override
public boolean apply(@Nullable String data) {
return data.startsWith(input);
}
}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment