diff --git a/lib/api/forms.js b/lib/api/forms.js index 9e335c9a1c..da4b4cbd0a 100644 --- a/lib/api/forms.js +++ b/lib/api/forms.js @@ -2,8 +2,22 @@ // https://github.com/jquery/jquery/blob/2.1.3/src/serialize.js var _ = require('lodash'), submittableSelector = 'input,select,textarea,keygen', + r20 = /%20/g, rCRLF = /\r?\n/g; +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; diff --git a/test/api/forms.js b/test/api/forms.js index 2812ec7d3b..f91df17d2a 100644 --- a/test/api/forms.js +++ b/test/api/forms.js @@ -128,4 +128,28 @@ describe('$(...)', function() { }); + describe('.serialize', function() { + + it('() : should get form controls', function() { + expect($('form#simple').serialize()).to.equal('fruit=Apple'); + }); + + it('() : should get nested form controls', function() { + expect($('form#nested').serialize()).to.equal('fruit=Apple&vegetable=Carrot'); + }); + + it('() : should not get disabled form controls', function() { + expect($('form#disabled').serialize()).to.equal(''); + }); + + it('() : should get multiple selected options', function() { + expect($('form#multiple').serialize()).to.equal('fruit=Apple&fruit=Orange'); + }); + + it('() : should encode spaces as +\'s', function() { + expect($('form#spaces').serialize()).to.equal('fruit=Blood+orange'); + }); + + }); + }); diff --git a/test/fixtures.js b/test/fixtures.js index b2b127d888..0c1a009451 100644 --- a/test/fixtures.js +++ b/test/fixtures.js @@ -67,5 +67,6 @@ exports.forms = [ '
', '', '', - '' + '', + '' ].join('');