supercobra
supercobra

Reputation: 16292

How to add a placeholder to a GWT text input field

Does any know of a Google Web Toolkit text input widget that would display a message inside the field when it is empty?

E.g. a first name field that would say: 'enter your first name' and when the user starts typing the label is removed to show the typed text.

How would you go about this?

Daniel

Upvotes: 14

Views: 12324

Answers (3)

Knarf
Knarf

Reputation: 2156

I would go with a UI framework that does this all for you (and more).

I am using GWT-Bootstrap 3 in all my projects and am more than happy about it : https://github.com/gwtbootstrap3/gwtbootstrap3

If you don't know bootstrap it is best to quickly go through a book of bootstrap3 so you now how the Grid system and other stuff works. Than you have headstart when using gwt-bootstrap 3.

Another one you can look at is https://github.com/GwtMaterialDesign/gwt-material which is a wrapper for Google Material. Not used it myself, but I think it not a bad choice.

Upvotes: 1

Daniel Hári
Daniel Hári

Reputation: 7774

With this solution you can define any additional properties in binder xml:

The solution:

public class MorePropertiesTextArea extends TextArea {
    private String moreProperties;

    public MorePropertiesTextArea() {}

    public void setMoreProperties(String moreProperties) {
        for (Entry<String, String> entry : parse(moreProperties).entrySet()) {
            getElement().setAttribute(entry.getKey(), entry.getValue());
        }
        this.moreProperties = moreProperties;
    }


    public String getMoreProperties() {
        return moreProperties;
    }

    private Map<String, String> parse(String moreProperties) {
        String[] pairStrings = moreProperties.split(";");
        HashMap<String, String> map = new HashMap<>();
        for (String pairString : pairStrings) {
            String[] pair = pairString.split("=");
            if(pair.length != 2)
                throw new IllegalArgumentException("at " + pair + " while parsing " + moreProperties + 
                        ". Use format like: 'spellcheck=false; placeholder=Write something here...'");
            map.put(pair[0].trim(), pair[1]);
        }
        return map;
    }

}

UI Binder xml:

<p2:MultiLineTextArea ui:field="taMultiLine" styleName="form-control muliLine"  
            moreProperties="spellcheck=false; placeholder=Write something here... " />

Result html:

<textarea class="form-control muliLine" spellcheck="false" placeholder="Write something here..."></textarea>

Upvotes: 1

Pablo Castilla
Pablo Castilla

Reputation: 2741

This does the work for me in a textarea:

yourInputField.getElement().setPropertyString("placeholder", "enter your first name");

I think it is a HTML5 feature.

Upvotes: 35

Related Questions