Skip to content

Commit

Permalink
serializeArray should not ignore input elements without value attributes
Browse files Browse the repository at this point in the history
serializeArray ignores input elements without value attributes. The
value attribute is optional for most types of input elements, however:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-value

In this case, input elements without a value attribute should be parsed
by this function, and default to an empty string value.
  • Loading branch information
rgladwell authored and jugglinmike committed Jan 22, 2017
1 parent 48721e8 commit 692e301
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 13 deletions.
26 changes: 13 additions & 13 deletions lib/api/forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,21 @@ exports.serializeArray = function() {
var name = $elem.attr('name');
var value = $elem.val();

// If there is no value set (e.g. `undefined`, `null`), then return nothing
// If there is no value set (e.g. `undefined`, `null`), then default value to empty
if (value == null) {
return 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 {
// 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' )};
}
return {name: name, value: value.replace( rCRLF, '\r\n' )};
}
// Convert our result to an array
}).get();
Expand Down
9 changes: 9 additions & 0 deletions test/api/forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,15 @@ describe('$(...)', function() {
]);
});

it('() : should serialize inputs without value attributes', function() {
expect($('<input name="fruit">').serializeArray()).to.eql([
{
name: 'fruit',
value: ''
}
]);
});

});

describe('.serialize', function() {
Expand Down

0 comments on commit 692e301

Please sign in to comment.