J Sprague
J Sprague

Reputation: 1038

Using ".value" of an <input> element works when run as Dart, fails when compiled to JavaScript

This question has mostly been answered elsewhere, but I thought I would mention my experience with this because of an interesting side-effect the Dart guys might be interested in knowing.

  enterPinDigits() {
      Element pinDigits = document.getElementById('pinDigits');
      pinDigits.value = "";

In the above, pinDigits is an HTML input element. When I code it as above, the editor tells me it doesn't recognize value as a valid field for the element.

HERE'S THE WEIRD PART: This code behaves perfectly fine running in the Chromium/Dart environment, but it fails horribly when compiled to Javascript. Odd inconsistency.

Upvotes: 1

Views: 82

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657018

getElementById returns a Node and the DartEditor can't know that it has an attribute value unless you state that it is an InputElement. If you make the variable of type Element it still has no value attribute.

var pinDigits = document.getElementById('pinDigits') as InputElement;

or

InputElement pinDigits = document.getElementById('pinDigits');

this way you also get proper autocompletion.

Dart2js uses type information for tree-shaking. It might drop the wrong code because of the wrong type annotation. In this case no type (var) is better than the wrong type. Actually Element isn't wrong so it might still be a bug.

Upvotes: 1

J Sprague
J Sprague

Reputation: 1038

I think I understand that this should be an InputElement, but I also found that a quick solution is to simply change the variable type from the Darty Element type to a generic var.

  var pinDigits = document.getElementById('pinDigits');

But as this subject has been somewhat addressed elsewhere, this post is mostly meant to clarify the earlier post and to point out the odd inconsistency when running as Dart vs Javascript.

Upvotes: 0

Related Questions