Skip to content

Commit

Permalink
use a selector to filter form elements
Browse files Browse the repository at this point in the history
  • Loading branch information
fb55 authored and jugglinmike committed Mar 28, 2015
1 parent 909245d commit 541815a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
19 changes: 7 additions & 12 deletions lib/api/forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
// 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;
rCRLF = /\r?\n/g;

exports.serializeArray = function() {
// Resolve all form elements from either forms or collections of form elements
Expand All @@ -17,18 +15,15 @@ exports.serializeArray = function() {
} 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') &&
}).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]`)
!rsubmitterTypes.test(type) &&
+ ':not(:submit, :button, :image, :reset, :file)'
// and are either checked/don't have a checkable state
($elem.attr('checked') || !rcheckableType.test(type));
+ ':matches([checked], :not(:checkbox, :radio))'
// Convert each of the elements to its value(s)
}).map(function(i, elem) {
).map(function(i, elem) {
var $elem = Cheerio(elem);
var name = $elem.attr('name');
var val = $elem.val();
Expand Down
11 changes: 11 additions & 0 deletions test/api/forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,17 @@ describe('$(...)', function() {
]);
});

it('() : shouldn\'t serialize the empty string', function() {
expect($('<input value=pineapple>').serializeArray()).to.eql([]);
expect($('<input name="" value=pineapple>').serializeArray()).to.eql([]);
expect($('<input name="fruit" value=pineapple>').serializeArray()).to.eql([
{
name: 'fruit',
value: 'pineapple'
}
]);
});

});

});

0 comments on commit 541815a

Please sign in to comment.