Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Dart Forms working example

Tags:

jquery

dart

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;    
    });
});
like image 966
basheps Avatar asked Dec 06 '12 13:12

basheps


1 Answers

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.

like image 164
Kai Sellgren Avatar answered Oct 27 '22 04:10

Kai Sellgren