Pregunta

In jQuery, there is a function to serialize a form element so for example I can submit it as an ajax request.

Let's say we have a form such as this:

<form id="form">
 <select name="single">
  <option>Single</option>
  <option selected="selected">Single2</option>
 </select>

 <input type="checkbox" name="check" value="check1" id="ch1">
 <input name="otherName" value="textValue" type="text">
</form>

If I do this with the help of jquery

var str = $( "form" ).serialize();
console.log(str);

the result would be

single=Single2&check=check1&otherName=textValue

Is there such functionality in dart's FormElement or I have to code it myself? Thanks.

¿Fue útil?

Solución

I came up with my own simple solution that might not work in all cases (but for me it is workikng). The procedure is this:

  1. First we need to extract all input or select element names and values from the form into Dart's Map, so the element name will be the key and value the value (e.g. {'single': 'Single2'}).
  2. Then we will loop through this Map and manually create the resulting string.

The code might look something like this:

FormElement form = querySelector('#my-form'); // To select the form
Map data = {};

// Form elements to extract {name: value} from
final formElementSelectors = "select, input";

form.querySelectorAll(formElementSelectors).forEach((SelectElement el) {
  data[el.name] = el.value; 
});

var parameters = "";

for (var key in data.keys) {
  if (parameters.isNotEmpty) {
    parameters += "&";
  }
  parameters += '$key=${data[key]}';
}

Parameters should now contain all the {name: value} pairs from the specified form.

Otros consejos

I haven't seen anything like that yet.

In this example Seth Ladd uses Polymers template to assign the form field values to a class which get's serialized.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top