package org.apache.wicket.examples.ajax.builtin;
import java.util.Locale;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.string.Strings;
@author
public class OnChangeAjaxBehaviorPage extends BasePage
{
private final IModel<String> inputModel = Model.of("");
private String getValue(String input)
{
if (Strings.isEmpty(input))
{
return "";
}
StringBuilder buffer = new StringBuilder();
Locale[] locales = Locale.getAvailableLocales();
for (final Locale locale : locales)
{
final String country = locale.getDisplayCountry();
if (country.toUpperCase(Locale.ROOT).startsWith(input.toUpperCase(Locale.ROOT)))
{
buffer.append(country);
buffer.append(' ');
}
}
return buffer.toString();
}
public OnChangeAjaxBehaviorPage()
{
Form<Void> form = new Form<>("form");
add(form);
final TextField<String> field = new TextField<>("field", inputModel);
form.add(field);
final Label userInput = new Label("userInput", inputModel);
userInput.setOutputMarkupId(true);
form.add(userInput);
final Label label = new Label("selectedValue", new Model<>(""));
label.setOutputMarkupId(true);
form.add(label);
OnChangeAjaxBehavior onChangeAjaxBehavior = new OnChangeAjaxBehavior()
{
@Override
protected void onUpdate(AjaxRequestTarget target)
{
label.setDefaultModelObject(getValue(field.getDefaultModelObjectAsString()));
target.add(label, userInput);
}
};
field.add(onChangeAjaxBehavior);
}
@Override
public void detachModels() {
super.detachModels();
inputModel.detach();
}
}