GWT SuggestBox with placeholder attribute

I am looking for a way to specify the placeholder attribute inside the <g:SuggestBox> in GWT. I know that the <input> element allows you to specify this attribute, but I decided to switch to the SuggestBox element instead of the input.

Can anybody help me?

+6
source share
3 answers

You must create your own SuggestBox widget, after which you can set the placeholder attribute for it. For instance:

 public class CustomSuggestBox extends SuggestBox { private String placeHolderText = ""; public String getPlaceHolderText() { return placeHolderText; } public void setPlaceHolderText(String text) { placeHolderText = text; getTextBox().getElement().setAttribute("placeHolder", placeHolderText); } } 

So, you can set this property in user interface binding.

 <widgets:CustomSuggestBox ui:field="cSuggestBox" placeHolderText="someText" /> 

PS: It only works in a modern browser. For the correct implementation of old browsers, also check the third-party wogwt library, it has a TextBoxWithPlaceholder , which extends the TextBox:

  /** * A text box that displays a placeholder string when empty * * <h3>CSS Style Rules</h3> * <ul class='css'> * <li>.wogwt-TextBoxWithPlaceholder { primary style }</li> * <li>.wogwt-TextBoxWithPlaceholder-placeholder { dependent style set when * the placeholder is displayed }</li> * </ul> */ 

In this case, you can send this TextBoxWithPlaceholder instance to the TextBoxWithPlaceholder constructor SuggestBox(SuggestOracle oracle, TextBoxBase box) .

+8
source

Subclass a SuggestBox will definitely work.
If you do not want to create an additional class, you can also easily add placeHolder to an existing SuggestBox by setting the attribute directly:

 SuggestBox suggestBox = new SuggestBox(); suggestBox.getElement().setAttribute("placeHolder", "SOME TEXT); 
+9
source

Note that you will get an exception if you call the getElement() method before the widget is added to the DOM. Therefore, if you want a solution that allows you to set placeholder text before adding it to the DOM and appear after adding it, you can connect to AttachEvent :

 SuggestBox suggestBox = new SuggestBox(); // com.google.gwt.event.logical.shared.AttachEvent.Handler suggestBox.addAttachHandler(new Handler() { @Override public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { suggestBox.getElement().setAttribute("placeHolder", "SOME TEXT); } } }); 
+2
source

Source: https://habr.com/ru/post/908630/


All Articles