Created
March 30, 2020 23:14
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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