如何知道Dart中是否选中了复选框或单选按钮?

时间:2012-11-01 17:03:37

标签: checkbox radio-button dart checked

我有一个复选框和一个单选按钮组,我想知道是否选中了复选框以及选中了哪个单选按钮。

如何在飞镖中执行此操作?

2 个答案:

答案 0 :(得分:8)

假设我们的HTML包含以下内容:

    <form >
      <input type="radio" name="gender" id="gender_male" value="male">Male<br>
      <input type="radio" name="gender" id="gender_female" value="female">Female
    </form>

    <form>
      <input type="checkbox" id="baconLover">I like bacon<br>
    </form>

您获取其值的Dart代码如下所示,我还添加了一个事件,以便知道何时单击该复选框。

import 'dart:html';

void main() {

  // Adds a click event when the checkbox is clicked
  query("#baconLover").on.click.add((MouseEvent evt) {
    InputElement baconCheckbox = evt.target;

    if (baconCheckbox.checked) {
      print("The user likes bacon");
    } else {
      print("The user does not like bacon");
    }

  });

  // Adds a click event for each radio button in the group with name "gender"
  queryAll('[name="gender"]').forEach((InputElement radioButton) {
    radioButton.onclick.listen((e) {
      InputElement clicked = e.target;
      print("The user is ${clicked.value}");
    });
  });

}

答案 1 :(得分:1)

我找到this solution 单选按钮,其中catch事件由“html”...我已将此解决方案用于我的项目。

<强> my_example.html

<polymer-element name="my-example">
  <template>
    <div on-change="{{updateRadios}}">
      Your favorite color is:
      <div>
        <label for="red">Red <input name="color" type="radio" id="red" value="red"></label>
      </div>
      <div>
        <label for="green">Green <input name="color" type="radio" id="green" value="green"></label>
      </div>
      <div>
        <label for="blue">Blue <input name="color" type="radio" id="blue" value="blue"></label>
      </div>
    </div>
    <div>
      You selected {{favoriteColor}}
    </div>
  </template>
  <script type="application/dart" src="my_example.dart"></script>
</polymer-element>

<强> my_example.dart

import 'package:polymer/polymer.dart';
import 'dart:html';

@CustomTag('my-example')
class MyExample extends PolymerElement {
  @observable String favoriteColor = '';

  MyExample.created() : super.created();

  void updateRadios(Event e, var detail, Node target) {
    favoriteColor = (e.target as InputElement).value;
  }

}