Reputation: 6251
I have a div in my html:
<div id="list_container_id"></div>
To which I add Checkbox(es) through dart
CheckboxInputElement cie = new CheckboxInputElement();
LabelElement label = new LabelElement();
cie.id="checkboxid_"+asdf;//unique id
label.htmlFor = 'checkboxid_'+asdf;//bind Label to checkbox
label.text = asdf;
list_container.children.add(cie);
list_container.children.add(label);
list_container.children.add(new Element.html("<br>"));//linebreak after the checkbox
later, I want to get a list of all values of the Checkboxes that are checked on Button click. The following code happens onClick:
List list = [];
for (CheckboxInputElement elem in list_container.children){
if(elem.checked){
list.add(elem.value);
}
}
As far as I understand it, that for loop goes trough every Checkbox that is in the list_container, but for some reason, it throws an Error when it reaches a label:
Breaking on exception: type 'LabelElement' is not a subtype of type 'CheckboxInputElement' of 'elem'.
I don't understand why the for loop even bothers with the Labels when I stated clearly that elem should be a CheckboxInputElement. How would be the right way to do this?
Upvotes: 0
Views: 165
Reputation: 402
querySelector("#list_container_id")
.querySelectorAll("input[type=checkbox]")
.forEach((CheckboxInputElement e) {
/* do work */
});
Upvotes: 1
Reputation: 658037
You don't state that it only should return CheckboxInputElement
you state that the variable holding the values processed in the loop should only hold CheckboxInputElement
s but the loop assigns every element it encounters.
This way you get only CheckboxInputElement
List list = [];
for (var elem in list_container.children.where((e) => e is CheckboxInputElement)){
if(elem.checked){
list.add(elem.value);
}
}
or
list.addAll(list_container.children
.where((e) => e is CheckboxInputElement && e.checked)
.map((e) => e.value));
or
list.addAll(querySelectorAll('#list_container_id input[type="checkbox"]')
.where((e) => e is CheckboxInputElement && e.checked)
.map((e) => e.value));
Upvotes: 2