Mike B
Mike B

Reputation: 5451

How do I clear a wicket AutoCompleteTextField after a choice is selected?

I'm using an AjaxFormComponentUpdatingBehavior to do some stuff when a choice is selected from an AutoCompleteTextField. After that stuff is done I want to clear the field but it's not behaving the way I expected it to.

Here're the relevant bits of code:

final AutoCompleteTextField<String> searchField =
    new AutoCompleteTextField<String>(id, model);

searchField.add(new AjaxFormComponentUpdatingBehavior("onchange") 
{           
    @Override
    protected void onUpdate(AjaxRequestTarget target) 
    {
        // Do stuff with the selected value here
        ...
        searchField.clearInput();
        target.addComponent(searchField);

    }                                               
});

I'm putting the value in a ListView and adding that to the target also. It gets updated correctly but the AutoCompleteTextField doesn't.

Upvotes: 1

Views: 2810

Answers (1)

Martin Strejc
Martin Strejc

Reputation: 4347

I think your example doesn't work, because you rerender the component on the client side using the model on the server side. If you reset the model value and repaint the component it has to work.

        searchField.setModelObject(null);
        target.addComponent(searchField);

However it is not neccessary to render the whole component, just clear the value on server and client side is enough.

The following example clears the model object and reset the field value by javascript (jQuery).

final AutoCompleteTextField<String> searchField =
    new AutoCompleteTextField<String>(id, model);
searchField.setOutputMarkupId(true);
searchField.add(new AjaxFormComponentUpdatingBehavior("onchange") 
{           
    @Override
    protected void onUpdate(AjaxRequestTarget target) 
    {
        // Do stuff with the selected value here
        ...
        searchField.clearInput();
        searchField.setModelObject(null);
        target.appendJavascript("$('#" + searchField.getMarkupId() + "').val('');");

    }                                               
});

If you are using Wicket prior 6.x then the jQuery is not included. You can use the following JS:

        target.appendJavascript("document.getElementById('" + searchField.getMarkupId() + "').value = '';");

Upvotes: 2

Related Questions