Ishan
Ishan

Reputation: 1006

Tracking changes in textbox in scala js

I've a text box in my html file and I want to detect whenever a user changes the value of it and determine its updated value also. html code for text box is :

<input type="text" name="amount" id="amount" value="0" onchange="Demo().change(id,value)">

and in my scala file, I've implemented a function 'change' as :

@JSExport
def change(id:String):Unit={
appendPar(document.body,"Text Box value is changed and the new value is : "+document.getElementById(id).getAttribute("value"))
}

But it is not working in my case. What am I doing wrong here ? Any suggestions ?

UPDATE : It is firing the event only when I press enter after altering the value in text box. Further, it is showing updated value as "0". How can I make it fetch from the text box instead of my pre defined value ?

Upvotes: 0

Views: 677

Answers (2)

Nikita
Nikita

Reputation: 2943

You can use input event instead of change if you can ignore IE<=9.

The DOM input event is fired synchronously when the value of an or element is changed

From MDN.

Note that for non-text/textarea inputs (e.g. checkboxes, radio buttons, etc.) there are additional browser compatibility caveats, but you can just use change event on those. See http://caniuse.com/#search=input for details.


I also don't see where the variable id is coming from in your code. You should pass the string "amount" instead of id if that's what you want, like this: Demo().change("amount"). That would be quite unreusable, but it should at least work.

If you want the method to be more generic, note that javascript passes an Event object to all event handlers, and it has a target key which contains the HTML element on which the event happened (in this case that would be your textarea). You can get then easily get the value of that target.

If this is confusing, I suggest you try to implement this in JS first, and then translate this into Scala. You don't want to be fighting on both fronts at the same time.

Upvotes: 2

gzm0
gzm0

Reputation: 14842

You'll need to use one of the onkey handlers. For example:

Note that IIRC, this will also trigger if the user moves around with the arrow keys. So if you really want to only be called if it changes, you'll need to introduce a variable and check:

var lastValue: String = ""

@JSExport
def change(id:String): Unit = {
  val newValue = document.getElementById(id).getAttribute("value")
  if (lastValue != newValue) {
    appendPar(document.body,
      "Text Box value is changed and the new value is : " + newValue)
    lastValue = newValue
  }
}

Upvotes: 0

Related Questions