LDropl
LDropl

Reputation: 944

Disable AjaxSubmitButton if text field is empty

I have a form with textfield and submit button and I would like to disable submit button if textfield is empty and enable it again as soon as textfield is not empty anymore

<form wicket:id="form">
    <div class="row">
    <textarea wicket:id="textMessage" rows="4" cols="70" maxlength="300"></textarea>
    </div>
    <div>
        <button wicket:id="submitButton" class="btn btn-sm btn-primary">
            Save
        </button>
    </div>
</form>
Form<Void> form = new Form<>("form");
TextArea<String> textMessageField = new TextArea<>("textMessage", textMessageModel);
Button submitBtn = new Button("submitButton");
submitBtn.add(new AjaxFormSubmitBehavior(form, "click") {
    @Override
    protected void onError(AjaxRequestTarget target) {
        target.add(getForm());
    }

    @Override
    protected void onSubmit(AjaxRequestTarget target) {
       //.....some code
    }

    @Override
    protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
        super.updateAjaxAttributes(attributes);
        attributes.setPreventDefault(true);
        }
    });
form.add(textMessageField);
form.add(submitBtn);

any ideas how to do it ?

Upvotes: 1

Views: 102

Answers (1)

magicmn
magicmn

Reputation: 1914

You need to add a AjaxFormComponentUpdatingBehavior or OnChangeAjaxBehavior to your text field.

TextArea<String> textMessageField = new TextArea<>("textMessage", textMessageModel);
Button submitBtn = new Button("submitButton") {
    @Override
    protected void onConfigure() {
        super.onConfigure();
        String obj = textMessageField.getModelObject();
        setEnabled(obj != null && !obj.isEmpty());
    }
};
submitBtn.setOutputMarkupId(true);
textMessageField.add(new OnChangeAjaxBehavior() {
    @Override
    protected void onUpdate(AjaxRequestTraget target) {
        target.add(submitBtn);
    }
});

Upvotes: 4

Related Questions