Using Vaadin: update Label text with TextField input after Button is clicked

I'm working on a simple Vaadin form where I want the text entered in a TextField to appear in a Label after the user clicks on a Button.

Here's the code snippet:

package com.example;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

public class TestForm extends UI {

    @WebServlet(value = "/TestForm", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = TestForm.class)
    public static class Servlet extends VaadinServlet {
    }

    private TextField textField;
    private Label label;
    private Button button;

    @Override
    protected void init(VaadinRequest request) {
        final VerticalLayout layout = new VerticalLayout();
        layout.setMargin(true);
        setContent(layout);

        textField = new TextField("Enter text");
        label = new Label();
        button = new Button("Click");    

        button.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                label.setValue(textField.getValue());
            }
        });

        layout.addComponent(textField);
        layout.addComponent(button);
        layout.addComponent(label);       

    }
}

However, when I click on the Button, nothing happens with the label and the web browser displays an error message:

Communication problem Take note of any unsaved data, and click here to continue. (SyntaxError) stack: eval@[native code] Jda BR Zc Xc line: 340: Unexpected token '<' - Original JSON-text: html>

What am I doing wrong?

Answer №1

UPDATE The issue was caused by having two servlet mappings in the web.xml file. I have resolved it by commenting out one of them:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="vaadinpokus" version="3.0">

  <display-name>vaadintest</display-name>
  <description>...</description>
  <context-param>
      <description>Vaadin production mode</description>
      <param-name>productionMode</param-name>
      <param-value>false</param-value>
  </context-param>
  <servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>com.vaadin.server.VaadinServlet</servlet-class>
    <init-param>
          <param-name>UI</param-name>
          <param-value>com.example.MyVaadinUI</param-value>
    </init-param>
    <async-supported>true</async-supported>
  </servlet>

  <servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

  <!--<servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/VAADIN/*</url-pattern>
  </servlet-mapping>-->
</web-app>

The issue should now be resolved. Thank you for providing your code. It makes troubleshooting much easier.

Answer №2

Why not switch from using lbl.setCaption to lbl.setValue? Give it a try!

btn.addClickListener(new Button.ClickListener() {
     public void buttonClick(ClickEvent event) {
         lbl.setValue(tf.getValue());
     }
 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JSLint error: Inconsistent use of spaces and tabs detected

I recently ran the code below through JSLint: $(document).ready(function() { /* Insert paragraph upon page load */ // Retrieve all header elements var header = document.getElementsByTagName('h1'), parent, ...

Sending target information as a property argument

I have encountered an issue with my app's two Bootstrap modals. It seems that many people are facing problems with opening the second modal. Is it possible to pass data-target and modal id properties as props in this manner: data-target={props.da ...

Is it possible to transfer data between two child components in Vue.js that share a common parent component?

In my project, I am working with 2 components that have a shared parent. My goal is to pass data from one child component to the other effectively. (I am specifically using vueJS 2 for this task) ...

What is the best method for choosing visible elements within a scrollable container?

Is there a way to retrieve the list of visible elements within a scrollable container? The number of elements that are visible on the screen changes as one scrolls, making it challenging to add a specific class to only the last two visible elements. Any s ...

javascript - Include new parameter in object literal and retrieve

I have a base object that I define using an object literal: var obj = { key1 : 'value1', key2 : 'value2' } Now, I want to pass this object to a function and extend it like this: myFunction( obj + { key3 : 'value3' ...

Utilize information from a JSON Array to populate a JavaScript Array

Is there a way to link the data from the $data variable in ajax.php to the this.products[] array in store.js? Both files are separate, so how can I achieve this? The webpage displays the database data returned by ajax.php as shown below: [{"0":"100001"," ...

Is it possible to caution users before refreshing the page, while still allowing them to

I have a script that displays a warning message to the user when they attempt to refresh the page. It works perfectly for that purpose. However, my issue is that this same alert pops up when a user clicks on a button or a link within the website itself. I ...

Guide to stopping available times from cycling through an array with the help of watch功能?

I am currently developing a booking application within Vue CLI. I have made use of vue-ctk-date-time-picker for selecting the date and time. My goal is to disable certain times based on the chosen date, but I am encountering an issue. The code I have writt ...

Setting form values using Angular 9

I am currently facing a challenge that I could use some assistance with. My dilemma involves integrating a new payment system, and I seem to be encountering some obstacles. Here is a snippet of what I have: options: PaystackOptions= { amount: 5000, emai ...

What is the method for combining two box geometries together?

I am looking to connect two Box Geometries together (shown in the image below) so that they can be dragged and rotated as one object. The code provided is for a drag-rotatable boxgeometry (var geometry1). What additional code do I need to include to join t ...

The absence of HTML and CSS is preventing the inclusion of an Ajax image viewer, back button, and

Currently, I am experimenting with jQuery and JavaScript to create an ajax overlay image viewer for a PHP website. After adding this code snippet at the end of the 'gallery page', I can successfully open the viewer and navigate using the next and ...

The error "Cannot invoke the indexOf method on an undefined element at order" is being encountered in Javascript

Looking for assistance with creating a function to sort a string where each word contains a single number from 1 to 9 (no 0). For instance, given the input: "is2 Thi1s T4est 3a", the desired output should be "Thi1s is2 3a T4est". The current code snippet ...

The system is unable to interpret the symbol property 'Symbol(Symbol.iterator)' because it is not defined

I have created a custom .any() method for Array objects to loop through an array and check if any item passes a specified function: Array.prototype.any = (comparator) => { for(let item of this){ if(comparator(item)){ return true ...

Create a JavaScript function that adds cells to a table, each containing an input field and a corresponding

I successfully developed a function that appends a table with rows and cells, then fills those cells with data from an array. However, I am now faced with the challenge of modifying it so that the generated cells contain an input field where the value= att ...

Is there a way to halt the compiler until an Ajax request is fully processed?

Within my form, there is a field labeled parent keywords as a secret key. The validation of this form using JavaScript functions smoothly. It is designed to check if the secret key is associated with any parent or not. If not, the value is set to 0 by defa ...

Preventing jQuery parser from turning arrays into objects

My JavaScript data file has the following structure: data = { items : [ {name: 'ABC'}, {name: 'CDF'} ] } After passing this data to $.ajax(type: 'POST', data: data), the converted data appears like this: it ...

Do the items appear on screen only once you start typing in AngularJS?

Most things are working well except for a couple of issues Code var app = angular.module("MyApp", []); app.filter('offset', function() { return function(input, start) { start = parseInt(start, 10); return input.slice(start); }; } ...

How to send the value of a JavaScript loop variable to PHP using AJAX

How can I send variables in a loop to a PHP file using AJAX? var lat; var lng; var array = [22.399602, 114.041176, 22.344043, 114.0168, 22.327529, 114.087181]; console.log(array); for (var i = 0; i < 6; i += 2) { lat = array[i]; console.log("l ...

Extracting data from an array using Angular

Currently, I am developing an Angular application that involves handling an array structured like the one below. [ { Code: "123", Details:[ { Id: "1", Name: "Gary" }, { ...

Do JavaScript functions operate synchronously or asynchronously?

Here is the JS code snippet I am working with: <script> first(); second(); </script> I need to ensure that second() will only be executed after first() has completed its execution. Is this the default behavior or do I need to make any modific ...