From 3b35ae4b04cd9746d5b6c34b8790d0d3f193d75e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20B=C3=B6hm?= Date: Tue, 22 Dec 2020 21:08:59 +0100 Subject: [PATCH] fix(attr): Fix handling of `undefined` as value (#1582) 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 --- lib/api/attributes.js | 15 ++++++--------- test/api/attributes.js | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/lib/api/attributes.js b/lib/api/attributes.js index ce2c78b15f..07162d1903 100644 --- a/lib/api/attributes.js +++ b/lib/api/attributes.js @@ -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])); @@ -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; diff --git a/test/api/attributes.js b/test/api/attributes.js index a6a3ababb1..2de914ec4a 100644 --- a/test/api/attributes.js +++ b/test/api/attributes.js @@ -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 () {