Getting a Wicket text box's value in an AJAX onchange event

sangameshwar picture sangameshwar · Apr 6, 2011 · Viewed 22.5k times · Source

When a user enters a number in a Wicket text field, I need to capture the value entered on an AJAX onchange event. How can I do this?

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Apr 6, 2011

Use an OnChangeAjaxBehavior, and your component model will be updated automatically. You can query the value by using component.getDefaultModelObject()

add(new TextField<String>(id, someModel)
    .add(new OnChangeAjaxBehavior(){

        private static final long serialVersionUID =
            2462233190993745889L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target){

            // Maybe you want to update some components here?

            // Access the updated model object:
            final Object value = getComponent().getDefaultModelObject();
            // or:
            final String valueAsString =
                ((TextField<String>) getComponent()).getModelObject();
        }
    }));

Actually, OnChangeAjaxBehavior is pretty aggressive because it registers a key listener, so in most cases new AjaxFormComponentUpdatingBehavior("onchange"){...} will work just as well, if you just want the onchange event.