Skip to content

Commit

Permalink
Merge pull request #31 from derbyjs/fix-input-number-decimals
Browse files Browse the repository at this point in the history
Fix inputting of decimals like "1.01" in <input type="number">
  • Loading branch information
ericyhwang authored Apr 15, 2020
2 parents 2ed44c8 + a07d12b commit 2c73757
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
13 changes: 13 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,19 @@ DynamicAttribute.prototype.update = function(context, binding) {
var element = binding.element;
var propertyName = !this.elementNs && UPDATE_PROPERTIES[binding.name];
if (propertyName) {
// Update via DOM property, short-circuiting if no update is needed.
// Certain properties must be strings, so for those properties, the value gets stringified.
//
// There is one special case, when updating the string `input.value` property with a number.
// If a user tries to type "1.01" in an `<input type="number">, then once they've typed "1.0",
// the context value is set to `1`, triggering this update function to set the input value to
// "1". That means typing "1.01" would be impossible without special handling to avoid
// overwriting an existing input value of "1.0" with a new value of "1".
if (element.tagName === 'INPUT' && propertyName === 'value' && typeof value === 'number') {
if (parseFloat(element.value) === value) {
return;
}
}
var propertyValue = (STRING_PROPERTIES[binding.name]) ?
this.stringify(value) : value;
if (element[propertyName] === propertyValue) return;
Expand Down
19 changes: 19 additions & 0 deletions test/test.mocha.js
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,25 @@ function testBindingUpdates(render) {
expect(input.value).equal('');
});

it('does not clobber input type="number" value when typing "1.0"', function() {
var template = new saddle.Template([
new saddle.Element('input', {
'type': new saddle.Attribute('number'),
'value': new saddle.DynamicAttribute(new expressions.Expression('amount')),
})
]);

var binding = render(template).pop();
var input = fixture.firstChild;

// Make sure that a user-typed input value of "1.0" does not get clobbered by
// a context value of `1`.
input.value = '1.0';
binding.context = getContext({amount: 1});
binding.update();
expect(input.value).equal('1.0');
});

it('updates "title" attribute', function() {
var template = new saddle.Template([
new saddle.Element('div', {
Expand Down

0 comments on commit 2c73757

Please sign in to comment.