Skip to content

Instantly share code, notes, and snippets.

@bitdivine
Created February 26, 2016 13:03
Show Gist options
  • Save bitdivine/dfb7daec6cb1a1e84d46 to your computer and use it in GitHub Desktop.
Save bitdivine/dfb7daec6cb1a1e84d46 to your computer and use it in GitHub Desktop.
HTML input type number with decimal precision.
(function(){
// Input field given to n decimal places. Degrades gracefully to standard numeric input.
// Usage: <input type="number" is="decimal-number" data-places="2" name="..." value="...">
try {
var proto = Object.create(HTMLInputElement.prototype);
proto.createdCallback = function() {
this.type = "number";
this.addEventListener("change", this.decimate);
this.value = parseFloat(this.value).toFixed(this.getAttribute('data-places'));
};
proto.decimate = function(){
this.value = parseFloat(this.value).toFixed(this.getAttribute('data-places'));
};
document.registerElement("decimal-number", {
prototype: proto,
extends: 'input'
});
} catch(e){}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment