Skip to content

Commit

Permalink
fix(attr): Fix handling of undefined as value (#1582)
Browse files Browse the repository at this point in the history
Fixes #554

This makes cheerio behave like jQuery with these values.

Tests were part of the issue above, contributed by @iwarren.

Co-authored-by: Ian Warren <[email protected]>
  • Loading branch information
fb55 and iwarren authored Dec 22, 2020
1 parent 0855be6 commit 3b35ae4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
15 changes: 6 additions & 9 deletions lib/api/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ var setAttr = function (el, name, value) {
*/
exports.attr = function (name, value) {
// Set the value (with attr map support)
if (typeof name === 'object' || value !== undefined) {
if (typeof name === 'object' || arguments.length > 1) {
if (typeof value === 'function') {
return domEach(this, function (i, el) {
setAttr(el, name, value.call(el, i, el.attribs[name]));
Expand Down Expand Up @@ -335,16 +335,13 @@ exports.val = function (value) {
case 'textarea':
return this.text(value);
case 'input':
if (this.attr('type') === 'radio') {
if (querying) {
return this.attr('value');
}

this.attr('value', value);
return this;
if (querying) {
return this.attr('value');
}

return this.attr('value', value);
this.attr('value', value);
return this;

case 'select':
var option = this.find('option:selected');
var returnValue;
Expand Down
17 changes: 17 additions & 0 deletions test/api/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,23 @@ describe('$(...)', function () {
expect($pear.attr('autofocus')).to.be(undefined);
expect($pear.attr('style')).to.equal('color:blue');
});

it('(chaining) setting value and calling attr returns result', function () {
var pearAttr = $('.pear').attr('foo', 'bar').attr('foo');
expect(pearAttr).to.equal('bar');
});

it('(chaining) setting attr to null returns a $', function () {
var $pear = $('.pear').attr('foo', null);
expect($pear).to.be.a($);
});

it('(chaining) setting attr to undefined returns a $', function () {
var $pear = $('.pear').attr('foo', undefined);
expect($('.pear')).to.have.length(1);
expect($('.pear').attr('foo')).to.be('undefined');
expect($pear).to.be.a($);
});
});

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

0 comments on commit 3b35ae4

Please sign in to comment.