简体   繁体   中英

CheckboxInputElement.onChange event not triggered

My code is simple but the line print("checky changed") is not run. It should be run because after registering the onChange listener, which should print a message when the checked status of the checkbox is changed, I change the checked status of the checkbox two times: first directly, then in a Timer executed three seconds later, every time with different values.

If I manually check or uncheck the checkbox, the message is printed.

I really need help with this problem: why the message "checky changed" is never printed when checky.checked 's value is changed programmatically?

I have this HTML code:

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>

    <script async type="application/dart" src="script.dart"></script>
    <script async src="packages/browser/dart.js"></script>
  </head>
  <body>
    <h1>Test</h1>

    <input type="checkbox" id="checky">
  </body>
</html>

and this Dart code:

import 'dart:html';
import 'dart:async';

void main() {
  CheckboxInputElement checky = querySelector('#checky');

  checky..checked = true
        ..onChange.listen((_) {
    print("checky changed");
  });

  checky.checked = false;    
  new Timer(const Duration(seconds: 3), () {
    checky.checked = true;    
  });
}

Thank you very much for any kind of help!

The forms option onchange doesn't fire programmatically. You need to execute the on change method after alter the checked property. Seb

You can dispatch onChange event manually:

import 'dart:html';
import 'dart:async';

void main() {
  CheckboxInputElement checky = querySelector('#checky');
  checky
      ..checked = true
      ..onChange.listen((_) {
        print("checky changed");
      });
  new Timer(const Duration(seconds: 1), () {
    checky.dispatchEvent(new Event("change"));
    checky.checked = !checky.checked;
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM