0

There's a form in an HTML page:

<form id="mainForm">
  <input type="text">
  </input>
</form>

and I can address that form in scala.js just fine via

dom.document.getElementById("mainForm")

Next I want to call

.send()

on the form to submit it. However, "send()" is not available as the

.getElementById()

from above returns an "Element" not an "HTMLFormElement", hence "send()" is not available.

How can I get/access the form "as" an "HTMLFormElement"?

Hannes
  • 3
  • 2

1 Answers1

2

By and large, this sort of external knowledge has to be injected manually. The simplest version is:

dom.document.getElementById("mainForm").asInstanceOf[HTMLFormElement]

Yes, that's a bit grungy, but it happens routinely at the interface between JavaScript / HTML and Scala.js: since the JS/HTML level is untyped, and the Scala level is strongly typed, you have to manually tell the Scala code what type you expect something to be.

If you're doing this sort of thing a lot, there are ways to semi-automate it (for example, examine the tag, determine that it's a FORM and do the cast based on that), but that's a bit higher-level -- getElementById is a raw DOM operation, and Scala.js intentionally doesn't add additional semantics to it.

(Many Scala.js apps avoid this by building the HTML in the program itself, so it's strongly-typed from the beginning.)

Justin du Coeur
  • 2,699
  • 1
  • 14
  • 19