Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed up serializeArray() and added multiple support #631

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ node_js:
script: make travis-test
matrix:
fast_finish: true
allow_failures:
- node_js: 0.11
4 changes: 2 additions & 2 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# cheerio [![Build Status](https://secure.travis-ci.org/cheeriojs/cheerio.svg?branch=master)](http://travis-ci.org/cheeriojs/cheerio)
# cheerio [![Build Status](https://secure.travis-ci.org/cheeriojs/cheerio.svg?branch=master)](http://travis-ci.org/cheeriojs/cheerio) [![Gittask](https://gittask.com/cheeriojs/cheerio.svg)](https://gittask.com/cheeriojs/cheerio)

Fast, flexible, and lean implementation of core jQuery designed specifically for the server.

Expand Down Expand Up @@ -441,7 +441,7 @@ $('li').not('.apple').length;
Function:

```js
$('li').filter(function(i, el) {
$('li').not(function(i, el) {
// this === el
return $(this).attr('class') === 'orange';
}).length;
Expand Down
54 changes: 54 additions & 0 deletions lib/api/forms.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// 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 _ = require('lodash'),
submittableSelector = 'input,select,textarea,keygen',
rCRLF = /\r?\n/g,
rcheckableType = /^(?:checkbox|radio)$/i,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i;

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(function() {
var $elem = Cheerio(this);
var type = $elem.attr('type');

// Verify elements have a name (`attr.name`) and are not disabled (`:disabled`)
return $elem.attr('name') && !$elem.is(':disabled') &&
// and cannot be clicked (`[type=submit]`) or are used in `x-www-form-urlencoded` (`[type=file]`)
!rsubmitterTypes.test(type) &&
// and are either checked/don't have a checkable state
($elem.attr('checked') || !rcheckableType.test(type));
// Convert each of the elements to its value(s)
}).map(function(i, elem) {
var $elem = Cheerio(elem);
var name = $elem.attr('name');
var val = $elem.val();

// If there is no value set (e.g. `undefined`, `null`), then return nothing
if (val == null) {
return null;
} else {
// If we have an array of values (e.g. `<select multiple>`), return an array of key/value pairs
if (Array.isArray(val)) {
return _.map(val, 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: val.replace( rCRLF, '\r\n' )};
}
}
// Convert our result to an array
}).get();
};
2 changes: 1 addition & 1 deletion lib/api/traversing.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
var _ = require('lodash'),
select = require('CSSselect'),
select = require('css-select'),
utils = require('../utils'),
domEach = utils.domEach,
uniqueSort = require('htmlparser2').DomUtils.uniqueSort,
Expand Down
3 changes: 2 additions & 1 deletion lib/cheerio.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ var api = [
require('./api/attributes'),
require('./api/traversing'),
require('./api/manipulation'),
require('./api/css')
require('./api/css'),
require('./api/forms')
];

/*
Expand Down
11 changes: 8 additions & 3 deletions lib/static.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Module dependencies
*/

var select = require('CSSselect'),
var select = require('css-select'),
parse = require('./parse'),
render = require('dom-serializer'),
_ = require('lodash');
Expand Down Expand Up @@ -106,7 +106,7 @@ exports.text = function(elems) {
len = elems.length,
elem;

for (var i = 0; i < len; i ++) {
for (var i = 0; i < len; i++) {
elem = elems[i];
if (elem.type === 'text') ret += elem.data;
else if (elem.children && elem.type !== 'comment') {
Expand Down Expand Up @@ -138,7 +138,12 @@ exports.parseHTML = function(data, context, keepScripts) {
parsed('script').remove();
}

return parsed.root()[0].children;
// The `children` array is used by Cheerio internally to group elements that
// share the same parents. When nodes created through `parseHTML` are
// inserted into previously-existing DOM structures, they will be removed
// from the `children` array. The results of `parseHTML` should remain
// constant across these operations, so a shallow copy should be returned.
return parsed.root()[0].children.slice();
};

/**
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
"node": ">= 0.6"
},
"dependencies": {
"CSSselect": "~0.4.0",
"css-select": "~1.0.0",
"entities": "~1.1.1",
"htmlparser2": "~3.8.1",
"dom-serializer": "~0.0.0",
"lodash": "~2.4.1"
"lodash": "^3.2.0"
},
"devDependencies": {
"benchmark": "~1.0.0",
Expand Down
120 changes: 120 additions & 0 deletions test/api/forms.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
var expect = require('expect.js'),
cheerio = require('../..'),
forms = require('../fixtures').forms;

describe('$(...)', function() {

var $;

beforeEach(function() {
$ = cheerio.load(forms);
});

describe('.serializeArray', function() {

it('() : should get form controls', function() {
expect($('form#simple').serializeArray()).to.eql([
{
name: 'fruit',
value: 'Apple'
}
]);
});

it('() : should get nested form controls', function() {
expect($('form#nested').serializeArray()).to.have.length(2);
var data = $('form#nested').serializeArray();
data.sort(function (a, b) {
return a.value - b.value;
});
expect(data).to.eql([
{
name: 'fruit',
value: 'Apple'
},
{
name: 'vegetable',
value: 'Carrot'
}
]);
});

it('() : should not get disabled form controls', function() {
expect($('form#disabled').serializeArray()).to.eql([]);
});

it('() : should not get form controls with the wrong type', function() {
expect($('form#submit').serializeArray()).to.eql([
{
name: 'fruit',
value: 'Apple'
}
]);
});

it('() : should get selected options', function() {
expect($('form#select').serializeArray()).to.eql([
{
name: 'fruit',
value: 'Orange'
}
]);
});

it('() : should not get unnamed form controls', function() {
expect($('form#unnamed').serializeArray()).to.eql([
{
name: 'fruit',
value: 'Apple'
}
]);
});

it('() : should get multiple selected options', function() {
expect($('form#multiple').serializeArray()).to.have.length(2);
var data = $('form#multiple').serializeArray();
data.sort(function (a, b) {
return a.value - b.value;
});
expect(data).to.eql([
{
name: 'fruit',
value: 'Apple'
},
{
name: 'fruit',
value: 'Orange'
}
]);
});

it('() : should get individually selected elements', function() {
var data = $('form#nested input').serializeArray();
data.sort(function (a, b) {
return a.value - b.value;
});
expect(data).to.eql([
{
name: 'fruit',
value: 'Apple'
},
{
name: 'vegetable',
value: 'Carrot'
}
]);

});

it('() : should standardize line breaks', function() {
expect($('form#textarea').serializeArray()).to.eql([
{
name: 'fruits',
value: 'Apple\r\nOrange'
}
]);
});

});

});
8 changes: 8 additions & 0 deletions test/api/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ describe('cheerio', function() {
expect(cheerio.parseHTML('<#if><tr><p>This is a test.</p></tr><#/if>') || true).to.be.ok();
});

it('(text) : should return an array that is not effected by DOM manipulation methods', function() {
var $ = cheerio.load('<div>');
var elems = $.parseHTML('<b></b><i></i>');

$('div').append(elems);

expect(elems).to.have.length(2);
});
});

describe('.contains', function() {
Expand Down
11 changes: 11 additions & 0 deletions test/fixtures.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,14 @@ exports.text = [
'<p>Apples, <b>oranges</b> and pears.</p>',
'<p>Carrots and <!-- sweetcorn --></p>'
].join('');

exports.forms = [
'<form id="simple"><input type="text" name="fruit" value="Apple" /></form>',
'<form id="nested"><div><input type="text" name="fruit" value="Apple" /></div><input type="text" name="vegetable" value="Carrot" /></form>',
'<form id="disabled"><input type="text" name="fruit" value="Apple" disabled /></form>',
'<form id="submit"><input type="text" name="fruit" value="Apple" /><input type="submit" name="submit" value="Submit" /></form>',
'<form id="select"><select name="fruit"><option value="Apple">Apple</option><option value="Orange" selected>Orange</option></select></form>',
'<form id="unnamed"><input type="text" name="fruit" value="Apple" /><input type="text" value="Carrot" /></form>',
'<form id="multiple"><select name="fruit" multiple><option value="Apple" selected>Apple</option><option value="Orange" selected>Orange</option><option value="Carrot">Carrot</option></select></form>',
'<form id="textarea"><textarea name="fruits">Apple\nOrange</textarea></form>'
].join('');