Using the jQuery input mask plugin with a Dart Web UI component

Issue

I’m trying to use an input mask jQuery plugin in Dart. The plugin works fine when the element I’m trying to add the mask to isn’t in a web component, but when I add it to a web component it no longer works. And for the code that doesn’t work I’m able to run $("#phone-number").mask("(999) 999-9999"); through the chrome console and it works fine.

This code works:

<!DOCTYPE html>

<html>
  <body>
    <input id="phone-number" type="text">

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script src="jquery.maskedinput.min.js"></script>
    <script type="application/dart">
      import 'package:js/js.dart' as js;

      void main() {
        js.scoped(() {
          var a = js.context.jQuery("#phone-number");
          a.mask("(999) 999-9999");
        });
      }
    </script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

This code does not work:

<!DOCTYPE html>

<html>
  <body>    
    <element name="x-phone-number">
      <template>
        <input id="phone-number">
      </template>
    </element>
    <x-phone-number></x-phone-number>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script src="jquery.maskedinput.min.js"></script>
    <script type="application/dart">
      import 'package:js/js.dart' as js;

      void main() {
        js.scoped(() {
          var a = js.context.jQuery("#phone-number");
          a.mask("(999) 999-9999");
        });
      }
    </script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

Solution

It’s likely down to components not being fully ready until after the main loop has run once, try adding a Timer to kick off the query like this…

<!DOCTYPE html>

<html>
  <body>    
    <element name="x-phone-number">
      <template>
        <input id="phone-number">
      </template>
    </element>
    <x-phone-number></x-phone-number>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script src="jquery.maskedinput.min.js"></script>
    <script type="application/dart">
      import 'package:js/js.dart' as js;
      import 'dart:async';

      void _postMainSetup() {
        js.scoped(() {
          var a = js.context.jQuery("#phone-number");
          a.mask("(999) 999-9999");
        });
      }

      void main() {
        Timer.run(_postMainSetup);
      }
    </script>
    <script src="packages/browser/dart.js"></script>
    <script src="packages/browser/interop.js"></script>
  </body>
</html>

I also added the interop.js script which is required in latest SDK as jsinterop functionality has been split out from dart.js.

Answered By – ianmjones

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *