I'm using ScalaJS and I want to read the value of an HTML input element.
Here's the HTML code:
<input id="nodeValue" type="number" step="1" />
And this is the Scala code:
object TutorialApp extends JSApp {
// ...
def addNode() = {
val nodeValue = document.getElementById("nodeValue").value.toInt
}
}
It doesn't compile, as
[error] TutorialApp.scala:42: value value is not a member of org.scalajs.dom.raw.Element
[error] val nodeValue = document.getElementById("nodeValue").value.toInt
In the documentation, I can't find the value attribute of org.scalajs.dom.raw.Element.
In the official basic tutorial it uses immediately to jQuery, but I'd avoid it since I'm working on a small proof of concept. I'm sure there's a way to use just the DOM API.
EDIT:
Going through the documentation I found the nodeValue method which returns a string. It says though that is null for "most node types".
Mine is number and indeed fails at runtime, returning null.
Another edit: it returns null also for a text input.
I feel a bit bewildered at this point.
thanks, Pietro
I assume the element you're fetching (nodeValue) is an <input> element.
getElementById does not know what kind of element nodeValue is. It does not have access to the .html to figure that out, and hence it returns a very generic Element. But in fact, you know that it is an input element, i.e., an org.scalajs.dom.html.Input. You can tell that to the compiler with .asInstanceOf[html.Input]. A generic Element does not have a value property, only Inputs have.
import org.scalajs.dom.html
val nodeValue = document.getElementById("nodeValue").asInstanceOf[html.Input].value.toInt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With