I'm currently trying to create a simple form in Dart with simply a username and email for registration purposes.
I cannot find a complete working example that I can test. If someone can explain how to convert the jQuery code below to Dart, I think that would clarify things greatly.
Also I've seen the FormData
class for Dart but no examples. Any help is appreciated.
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#responseDiv").empty();
$("#responseDiv").html(info);
});
$("#myForm").submit( function() {
return false;
});
});
First import the two libraries:
import 'dart:html';
import 'dart:convert';
Then we define a serializer function:
serializeForm(FormElement form) {
var data = {};
// Build data object.
form.querySelectorAll('input,select').forEach((Element el) {
if (el is InputElement)
data[el.name] = el.value;
});
return data;
}
It simply serializes a form into a Map
of data. I am not aware of a Dart form serializer, there may be some package for that purpose. Note that the above example only deals with inputs.
Next we assume the following HTML:
<form id="myForm" action="/bar">
<label>Foo:</label>
<input type="text" name="foo" value="bar" />
</form>
<button id="mySubmit">Send it</button>
And last our Dart client-side code for form handling:
main() {
FormElement form = querySelector('#myForm');
ButtonElement button = querySelector('#mySubmit');
button.onClick.listen((e) {
var req = new HttpRequest();
req.onReadyStateChange.listen((ProgressEvent e) {
if (req.readyState == HttpRequest.DONE) {
print('Data submitted!');
}
});
req.open('POST', form.action);
req.send(JSON.encode(serializeForm(form)));
});
}
This should get you started.
You might also want to use Polymer for your forms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With