3

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

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

Would it be better to generate the html directly in scalajs? Like with scalatags?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.