Inputs label changes according to input

In this example notebook, I’m trying to change a text form label according to its own input, which spits out an obvious circular reference error.

How can I change the label of a form using some validation? Is checkValidity() involved?

Here’s the code:

viewof number = Inputs.text({
  label: "Even number " + isEven(number) ? "✅" : "❌"
})
function isEven(number) {
  return number % 2 == 0;
}
1 Like

Does this help?
Comparing Changing Inputs Label to Changing Inputs Label | Observable (observablehq.com)

… It’s really not so easy to change the Label field. It’s always interpreted as a string. So rendering in the outputs from another cell doesn’t really work. I tried instead to construct view that might approximate what you’re after.

1 Like

Nice workaround!

You can work with references inside your cell, before returning the element. Example:

viewof number = {
  const myLabel = htl.html`<span>`;
  const input = Inputs.text({ label: myLabel }); // pass in a reference to the Element
  onInput(); // set the initial state
  input.addEventListener("input", onInput);
  return input;

  function onInput() {
    myLabel.textContent = `Even number: ${ isEven(+input.value) ? "✅" : "❌" }`;
  }
}
1 Like

@mootari If I drop your code into a single JS cell, I get

viewof number = RuntimeError: label is not defined

Do I need an additional cell with content?

Whoops, that’s what I get for editing code in Discourse. Fixed! :pray:

1 Like

myLabel.textContent = `Even number: ${ isEven("" + input.value) ? "✅" : "❌" }`;

The added "" forces a string concatenation. An empty string was returning 0.

I’d argue that you shouldn’t even pass an empty string to isEven and instead display nothing in that case.

The example I gave using isEven was just that: a simplified example.

I’m actually verifying if a string of 9 digits (e.g., 05231092153, the Brazilian equivalent of the SSN) satisfies a test. The zero on the left matters.