summaryrefslogtreecommitdiff
path: root/bin/wiki/ImportarDesdeURL/node_modules/cheerio/lib/api/forms.js
blob: b66f162cd99eb1016f6c0f097c058d630dd7cfc3 (plain)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// https://github.com/jquery/jquery/blob/2.1.3/src/manipulation/var/rcheckableType.js
// https://github.com/jquery/jquery/blob/2.1.3/src/serialize.js
var submittableSelector = 'input,select,textarea,keygen',
    r20 = /%20/g,
    rCRLF = /\r?\n/g,
    _ = {
      map: require('lodash/map')
    };

exports.serialize = function() {
  // Convert form elements into name/value objects
  var arr = this.serializeArray();

  // Serialize each element into a key/value string
  var retArr = _.map(arr, function(data) {
    return encodeURIComponent(data.name) + '=' + encodeURIComponent(data.value);
  });

  // Return the resulting serialization
  return retArr.join('&').replace(r20, '+');
};

exports.serializeArray = function() {
  // Resolve all form elements from either forms or collections of form elements
  var Cheerio = this.constructor;
  return this.map(function() {
      var elem = this;
      var $elem = Cheerio(elem);
      if (elem.name === 'form') {
        return $elem.find(submittableSelector).toArray();
      } else {
        return $elem.filter(submittableSelector).toArray();
      }
    }).filter(
        // Verify elements have a name (`attr.name`) and are not disabled (`:disabled`)
        '[name!=""]:not(:disabled)'
        // and cannot be clicked (`[type=submit]`) or are used in `x-www-form-urlencoded` (`[type=file]`)
        + ':not(:submit, :button, :image, :reset, :file)'
        // and are either checked/don't have a checkable state
        + ':matches([checked], :not(:checkbox, :radio))'
    // Convert each of the elements to its value(s)
    ).map(function(i, elem) {
      var $elem = Cheerio(elem);
      var name = $elem.attr('name');
      var value = $elem.val();

      // If there is no value set (e.g. `undefined`, `null`), then default value to empty
      if (value == null) {
        value = '';
      }

      // If we have an array of values (e.g. `<select multiple>`), return an array of key/value pairs
      if (Array.isArray(value)) {
        return _.map(value, function(val) {
          // We trim replace any line endings (e.g. `\r` or `\r\n` with `\r\n`) to guarantee consistency across platforms
          //   These can occur inside of `<textarea>'s`
          return {name: name, value: val.replace( rCRLF, '\r\n' )};
        });
      // Otherwise (e.g. `<input type="text">`, return only one key/value pair
      } else {
        return {name: name, value: value.replace( rCRLF, '\r\n' )};
      }
    // Convert our result to an array
    }).get();
};