Friday, March 30, 2012

Re: How to get text from textarea as html

TextArea.getText() gives you exactly the text with all white spaces and line breaks.

Its just that you can't put that text into a HTML element, because the browser will remove every line break and also trims down the white spaces to one.

If you want to display that text, you have to use the <pre> tag or apply the CSS property "white-space:pre" to any HTML element that should contain the text from the textarea.

Example:

  @Override
  public void onModuleLoad() {
    final Label label = new Label();
    final Label preLabel = new Label();
    preLabel.getElement().getStyle().setProperty("whiteSpace", "pre");
    final PreElement pre = Document.get().createPreElement();
    final TextArea textarea = new TextArea();
    textarea.setSize("300px", "200px");
    Button button = new Button("Read text");
    button.addClickHandler(new ClickHandler() {
      @Override
      public void onClick(final ClickEvent event) {
        String text = textarea.getText();
        System.out.println(text);
        label.setText(text);
        preLabel.setText(text);
        pre.setInnerText(text);
      }
    });
    RootPanel.get().add(textarea);
    RootPanel.get().add(button);
    RootPanel.get().add(new Label("------ LABEL -------"));
    RootPanel.get().add(label);
    RootPanel.get().add(new Label("------ PRE ELEMENT -------"));
    RootPanel.get().getElement().appendChild(pre);
    RootPanel.get().add(new Label("------ LABEL (with CSS white-space:pre applied) -------"));
    RootPanel.get().add(preLabel);
  }

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-web-toolkit/-/2-yl_Q62bewJ.
To post to this group, send email to google-web-toolkit@googlegroups.com.
To unsubscribe from this group, send email to google-web-toolkit+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-web-toolkit?hl=en.

No comments:

Post a Comment