Skip to content

Commit 3b35ae4

Browse files
fb55iwarren
andauthored
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 <[email protected]>
1 parent 0855be6 commit 3b35ae4

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed

lib/api/attributes.js

+6-9
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ var setAttr = function (el, name, value) {
8686
*/
8787
exports.attr = function (name, value) {
8888
// Set the value (with attr map support)
89-
if (typeof name === 'object' || value !== undefined) {
89+
if (typeof name === 'object' || arguments.length > 1) {
9090
if (typeof value === 'function') {
9191
return domEach(this, function (i, el) {
9292
setAttr(el, name, value.call(el, i, el.attribs[name]));
@@ -335,16 +335,13 @@ exports.val = function (value) {
335335
case 'textarea':
336336
return this.text(value);
337337
case 'input':
338-
if (this.attr('type') === 'radio') {
339-
if (querying) {
340-
return this.attr('value');
341-
}
342-
343-
this.attr('value', value);
344-
return this;
338+
if (querying) {
339+
return this.attr('value');
345340
}
346341

347-
return this.attr('value', value);
342+
this.attr('value', value);
343+
return this;
344+
348345
case 'select':
349346
var option = this.find('option:selected');
350347
var returnValue;

test/api/attributes.js

+17
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,23 @@ describe('$(...)', function () {
137137
expect($pear.attr('autofocus')).to.be(undefined);
138138
expect($pear.attr('style')).to.equal('color:blue');
139139
});
140+
141+
it('(chaining) setting value and calling attr returns result', function () {
142+
var pearAttr = $('.pear').attr('foo', 'bar').attr('foo');
143+
expect(pearAttr).to.equal('bar');
144+
});
145+
146+
it('(chaining) setting attr to null returns a $', function () {
147+
var $pear = $('.pear').attr('foo', null);
148+
expect($pear).to.be.a($);
149+
});
150+
151+
it('(chaining) setting attr to undefined returns a $', function () {
152+
var $pear = $('.pear').attr('foo', undefined);
153+
expect($('.pear')).to.have.length(1);
154+
expect($('.pear').attr('foo')).to.be('undefined');
155+
expect($pear).to.be.a($);
156+
});
140157
});
141158

142159
describe('.prop', function () {

0 commit comments

Comments
 (0)