Text input component for entering measurements with automatic unit detection and conversion. Pure HTML/JS/CSS, no dependencies.
Text input component for entering measurements with automatic unit detection and conversion. Pure HTML/JS/CSS, no dependencies.
Type 5' 11" or 180cm or 1.8m and it figures out what you mean.
<link rel="stylesheet" href="css/unit-input.css">
<div id="height"></div>
<script type="module">
import UnitInput from './js/unit-input.js';
const input = new UnitInput(document.getElementById('height'), {
defaultUnit: 'ft',
precision: 2,
onChange: (value) => console.log(value)
});
</script>
Or as a web component:
<unit-input default-unit="cm" precision="1"></unit-input>
4', 4ft, 4 ft → feet4", 4in, 4 in → inches4' 11", 4ft 11in, 4' 11 → feet + inches1.8m, 1.8 m → meters180cm, 180 cm → centimeters1524mm → millimetersinput.getValue() // { unit: 'ft', displayValue: '5.92', mm: 1804.416 }
input.getValueInUnit('m') // 1.804416
input.getValueInMm() // 1804.416
input.setValue(180, 'cm')
input.setValue({ feet: 5, inches: 11 }, 'ft+in')
input.reset()
input.setEnabled(false)
input.destroy()
The converter and parser work independently if you just need those:
import convert from './js/convert.js';
convert(6, 'ft').to('m'); // 1.8288
convert(180, 'cm').to('in'); // 70.866...
import InputParser from './js/input-parser.js';
InputParser.parse("5' 11\""); // { value: { feet: 5, inches: 11 }, unit: 'ft+in' }
InputParser.parse("180cm"); // { value: 180, unit: 'cm' }
InputParser.detectUnit("5'"); // 'ft'
Values are stored internally in millimeters. When you change units via the dropdown, it converts. Uses a Decimal polyfill for precision so you don’t get floating point weirdness.
I needed it for another project.