kangax / protolicious

prototype.js tidbits

This URL has Read+Write access

protolicious / form.methods.js
100644 27 lines (25 sloc) 0.779 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Form#unserialize(@element, source) -> Element
* - @element(FormElement): Form element to fill with values
* - source(Object | String): Source object where field values are taken from
*
* Fills form with values of a given object `source`.
* Each propertie name of `source` is compared to name attribute of a form element.
*
* $('myForm').unserialize()
*
**/
Form.Methods.unserialize = function(element, source) {
  if (!(element = $(element)))
    throw new Error('DOMElement is required');
  
  source = Object.isString(source)
    ? source.toQueryParams()
    : source;
  
  element.getElements().each(function(element) {
    for (var name in source) {
      if (name == element.name)
        element.setValue(source[name]);
    }
  })
  return element;
};