Skip to content
This repository has been archived by the owner on Mar 20, 2021. It is now read-only.

don't allow checked='false' on inputs #354

Merged
merged 5 commits into from
Apr 8, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions src/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
56 changes: 56 additions & 0 deletions test/src/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 '<input type="'+type+'" name="bat" value="'+inputValue+'">';
}
});

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();
});
});
});
});