I'm working on a Django project and one of the forms won't submit. I figured out that the culprit is some JavaScript that formats the currency input (when I remove the JS or remove the input type="currency"
, it submits)
This is my simplified form - the JS is from html5 input for money/currency
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP'
// format inital value
onBlur({
target: currencyInput
})
// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)
function localStringToNumber(s) {
return Number(String(s).replace(/[^0-9.-]+/g, ""))
}
function onFocus(e) {
var value = e.target.value;
e.target.value = value ? localStringToNumber(value) : ''
}
function onBlur(e) {
var value = e.target.value
var options = {
maximumFractionDigits: 2,
currency: currency,
style: "currency",
currencyDisplay: "symbol"
}
e.target.value = value ?
localStringToNumber(value).toLocaleString(undefined, options) :
''
}
<form action="{% url 'create_goal' %}" method="post">
<h4 class="mb-3" id="create">Create a Savings Goal</h4>
<input type="text" class="form-control" id="goalName" name="goalName" value="" required>
<input type="currency" min="0" pattern="^\d*(\.\d{0,2})?$" class="form-control" id="goal" name="goal" required>
<button type="submit" class="btn btn-secondary btn-block">Add Goal</button>
</form>