diff --git a/src/form.js b/src/form.js index 206f11dd..9ba22709 100644 --- a/src/form.js +++ b/src/form.js @@ -131,10 +131,9 @@ _.extend(Thorax.View.prototype, { if (!_.isUndefined(value)) { //will only execute if we have a name that matches the structure in attributes var isBinary = type === 'checkbox' || type === 'radio'; - if (isBinary && _.isBoolean(value)) { - $element.attr('checked', value); - } else if (isBinary) { - $element.attr('checked', value == $element.val()); + if (isBinary) { + value = _.isBoolean(value) ? value : value === $element.val(); + $element[value ? 'attr' : 'removeAttr']('checked', 'checked'); } else { $element.val(value); } diff --git a/test/src/form.js b/test/src/form.js index 7d5acb06..eb832dcb 100644 --- a/test/src/form.js +++ b/test/src/form.js @@ -294,4 +294,60 @@ describe('form', function() { view.render(); expect(view.serialize()).to.eql({foo: true}); }); + + describe( "populate checked", function() { + var view; + + function renderedFormView(type, inputValue, attrValue) { + var newView = new FormView({ + template: function() { + return ''; + } + }); + + var attributes = { bat: attrValue }; + var model = new Thorax.Model(attributes); + newView.setModel(model); + newView.render(); + return newView; + } + + function viewCheckedAttr() { + return view.$('input[name="bat"]').eq(0).attr('checked'); + } + + function expectChecked() { + expect(viewCheckedAttr()).to.equal('checked'); + } + + function expectNotChecked() { + // don't be the string 'false', instead be boolean false, since the attr is non-existent + expect(viewCheckedAttr()).to.not.equal('false').and.to.be['false']; + } + + describe( "checkbox", function() { + it( "should populate input attribute 'checked' with value 'checked' if set", function() { + view = renderedFormView('checkbox', 'man', 'man'); + expectChecked(); + }); + + it( "should not populate input attribute 'checked' if not set", function() { + view = renderedFormView('checkbox', 'man', 'woman'); + expectNotChecked(); + }); + }); + + describe( "radio", function() { + // this is currently broken on fruit-loops. see here: https://github.com/kpdecker/cheerio/blob/master/lib/api/attributes.js#L143 + xit( "should populate input attribute 'checked' with value 'checked' if set", function() { + view = renderedFormView('radio', 'man', 'man'); + expectChecked(); + }); + + it( "should not populate input attribute 'checked' if not set", function() { + view = renderedFormView('radio', 'man', 'woman'); + expectNotChecked(); + }); + }); + }); });