Search code examples
htmljsondartdart-html

How to check if InputElement is a checkbox in Dart


I'm serializing some forms to JSON in dart:html

Map jsonifyForm(String formQuery){

  FormElement form = querySelector(formQuery);

  Map<String, String> data = {};

  List<InputElement> inputs = form.querySelectorAll("input.json");
  for (InputElement input in inputs) {

    if (input is CheckboxInputElement){
      print("checkbox: " + input.name + "|" + input.checked.toString());
      data.putIfAbsent(input.name, () => input.checked);
    } else {
      print("text: " + input.name + "|" + input.value);
      data.putIfAbsent(input.name, () => input.value);
    }
  }

  print(data);
  return data;
}

I have about a 100 input fields on the page, followed by only one checkbox:

<label>First Name</label>
<input type="text" class="form-control tip json" placeholder="First Name" name="firstName" value="" data-toggle="tooltip" data-placement="top" title="First Name"/>


<label>Last Name</label>
<input type="text" class="form-control tip json" placeholder="Last Name" name="lastName" value="" data-toggle="tooltip" data-placement="top" title="Last Name"/>

...

<label class="form-control tip" data-placement="top" title="VAT On Goods" data-toggle="tooltip">
<input class="json" type="checkbox" name="vatOnGoods">
VAT on goods
</label>

When I call jsonifyForm, I'm seeing that all inputs are being treated as checkboxes:

checkbox: firstName|false
checkbox: lastName|false
...
checkbox: vatOnGoods|false

{firstName: false, lastName: false, ..., vatOnGoods: false}

Is this a bug or am I doing something wrong here?


Solution

  • The class CheckboxInputElement only provides the value and checked attributes. I am still wondering why it says that those are all checkboxes. But you can just check the type attribute:

    if(input.type == 'checkbox')
    

    to check the type of the checkbox.