1

Is there a way to read an input value as in JavaScript using java - elemental2? My entire code looks like this:

    public void onModuleLoad() {
        document.body.style.margin = MarginUnionType.of("0");

        document.body.appendChild(navigation());
        document.body.appendChild(mainSection());
    }

    // *********************** //
    // Elemental methods

    public static HTMLElement mainSection() {
        // create list
        HTMLElement ul = (HTMLElement) document.createElement("ul");
        ul.style.listStyle = "none";
        HTMLElement li = (HTMLElement) document.createElement("li");
        li.textContent = "Tasks";
        ul.appendChild(li);
        return ul;
    }

    public static HTMLElement navigation() {
        // create button
        HTMLButtonElement button = (HTMLButtonElement) document.createElement("button");
        button.textContent = "Add Task";
        button.addEventListener("click", evt -> onAddTask());

        // create main nav
        HTMLElement mainNav = (HTMLElement) document.createElement("nav");
        mainNav.className = "main-nav";
        mainNav.appendChild(addInput());
        mainNav.appendChild(button);

        return mainNav;
    }

    public static HTMLInputElement addInput() {
        // create input
        HTMLInputElement input = (HTMLInputElement) document.createElement("input");
        input.placeholder = "Enter your name here";
        input.id = "tasks-input";
        return input;
    };

    public static void onAddTask() {
        alert(document.getElementById("tasks-input").getAttribute("value"));
    }

}

Basically when I click on the button I want to print whatever I typed into the input. Thanks!

1 Answers1

1

Generally with elemental2 you can use a DOM API object's property directly. So according to: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement you can do the following in java with elemental2:

HTMLInputElement input;
input.value = "foo";
String value = input.value;
Robert Newton
  • 1,344
  • 12
  • 19
  • Hi, thanks, but the value for my input in not set in the code as input.value = 'foo' but the input is filled in via DOM – marincean adrian Jul 19 '22 at 06:36
  • That 2nd line was just an example of setting the value in code. The 3rd line is what you wanted to know -- how to read the value of the input. – Robert Newton Jul 20 '22 at 00:02