add focus and blur events on inputs

This commit is contained in:
Vaclav Uruba 2023-08-25 16:24:35 +02:00
parent 7199a1e99d
commit 6998060494
Signed by: uruba
GPG Key ID: 9D8E987C4B2E1E9C
2 changed files with 47 additions and 5 deletions

View File

@ -24,7 +24,11 @@
}
function refreshPrices(calcValues: CalculatorValues) {
console.log(calcValues);
if (!validateCalculatorValues(calcValues)) {
// Calculator values are invalid, we don't want to refresh the prices.
return false;
}
if (
calcValues.basePrice !== calcValuesCache.basePrice ||
calcValues.vatRate !== calcValuesCache.vatRate
@ -38,6 +42,38 @@
refreshCache(calcValues);
}
function validateCalculatorValues(calcValues: CalculatorValues) {
let property: keyof typeof calcValues;
for (property in calcValues) {
if (calcValues[property] === null) {
return false;
}
}
return true;
}
function handleFocus(event: Event) {
const element = event.target;
if (element instanceof HTMLInputElement) {
if (element.value === '0') {
element.value = '';
}
}
}
function handleBlur(event: Event) {
const element = event.target;
if (element instanceof HTMLInputElement) {
if (element.value === '') {
element.value = '0';
}
}
}
$: refreshPrices(calcValues);
const invalidNumberErrorText = 'Zadejte platné číslo.';
@ -52,6 +88,8 @@
max="100"
bind:value={calcValues.vatRate}
class:invalid={calcValues.vatRate === null}
on:focus={handleFocus}
on:blur={handleBlur}
/>
{#if calcValues.vatRate === null}
<p class="invalid">{invalidNumberErrorText}</p>
@ -63,6 +101,8 @@
min="0"
bind:value={calcValues.basePrice}
class:invalid={calcValues.basePrice === null}
on:focus={handleFocus}
on:blur={handleBlur}
/>
{#if calcValues.basePrice === null}
<p class="invalid">{invalidNumberErrorText}</p>
@ -74,6 +114,8 @@
min="0 "
bind:value={calcValues.finalPrice}
class:invalid={calcValues.finalPrice === null}
on:focus={handleFocus}
on:blur={handleBlur}
/>
{#if calcValues.finalPrice === null}
<p class="invalid">{invalidNumberErrorText}</p>

View File

@ -1,6 +1,6 @@
export default interface CalculatorValues {
basePrice: number;
vatRate: number;
vatAmount: number;
finalPrice: number;
basePrice: number|null;
vatRate: number|null;
vatAmount: number|null;
finalPrice: number|null;
}