Skip to content

Instantly share code, notes, and snippets.

@psergi
Created March 30, 2020 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save psergi/72f99b792a967525ffe2e319cf746101 to your computer and use it in GitHub Desktop.
Save psergi/72f99b792a967525ffe2e319cf746101 to your computer and use it in GitHub Desktop.
Stimulus controller to handle dollar based user input when the backend is expecting cents
import { Controller } from 'stimulus';
export default class extends Controller {
onInput = (e) => this.updateHiddenInput(e.target.value);
connect() {
this.element.addEventListener('input', this.onInput);
this.initializeHiddenInput();
this.initializeInput();
}
disconnect() {
this.element.removeEventListener('input', this.onInput);
}
get value() {
return this.element.getAttribute('value'); // use getAttribute to bypass autocomplete issues
}
initializeInput() {
this.element.removeAttribute('name');
if (this.value) {
this.element.value = ((parseFloat(this.value) || 0) / 100).toFixed(2);
}
}
initializeHiddenInput() {
this.hiddenInput = this.buildHiddenInput();
this.element.insertAdjacentElement('afterend', this.hiddenInput);
}
buildHiddenInput() {
const hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', this.element.getAttribute('name'));
hiddenInput.value = this.value;
return hiddenInput;
}
updateHiddenInput(value) {
this.hiddenInput.value = this.parseInputAsCents(value);
}
parseInputAsCents(value) {
const parsedValue = value.replace(/[^0-9.]/gi, '');
if (parsedValue) {
return (parseFloat(parsedValue) || 0) * 100;
}
return '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment