unit-of-measurement-input

Text input component for entering measurements with automatic unit detection and conversion. Pure HTML/JS/CSS, no dependencies.

0
0
0
JavaScript
public

Unit Input

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.

Usage

<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>

Input Formats

  • 4', 4ft, 4 ft → feet
  • 4", 4in, 4 in → inches
  • 4' 11", 4ft 11in, 4' 11 → feet + inches
  • 1.8m, 1.8 m → meters
  • 180cm, 180 cm → centimeters
  • 1524mm → millimeters

API

input.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()

Standalone Utilities

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'

How It Works

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.

Why?

I needed it for another project.

v0.3.3[beta]