Hello. I created a Laravel Blade component that generates an input field where only numbers can be entered, and it also renders a formatted display below the input field. My problem is that when I use the live parameter and type slowly into the input field, the entered numbers disappear, as if they were constantly being overwritten.
Component contents: resources\views\components\numeric-mask-input.blade.php
@props([
'name',
'label' => '',
'suffix' => '',
'wrapperClass' => 'mb-4',
'inputClass' => '',
'min' => 0,
'max' => 99999999999,
'required' => false,
'disabledCondition' => false,
])
@php
$hasError = $errors->has($name);
@endphp
<div class="{{ $wrapperClass }}">
@if($label)
<label for="{{ $name }}" class="block text-sm font-semibold text-gray-700 mb-1">
{{ $label }}
@if($required)
<span class="text-red-600">*</span>
@endif
</label>
@endif
<div
x-data="{
raw: '',
value: @entangle($attributes->wire('model')).live,
}"
x-init="
const mask = IMask($refs.input, {
mask: Number,
thousandsSeparator: '',
min: {{ $min }},
max: {{ $max }},
});
if (value !== null && value !== undefined && value !== '') {
mask.unmaskedValue = value.toString();
raw = mask.value;
}
$watch('value', newVal => {
if (newVal !== mask.unmaskedValue) {
mask.unmaskedValue = newVal?.toString() ?? '';
raw = mask.value;
}
});
mask.on('accept', () => {
raw = mask.value;
value = mask.unmaskedValue;
});
"
class="relative"
>
<input
x-ref="input"
x-model="raw"
type="text"
id="{{ $name }}"
name="{{ $name }}"
autocomplete="off"
@if($disabledCondition) disabled @endif
{{ $attributes->merge([
'class' => "text-paragraph-color px-5 outline-none border " .
($hasError ? 'border-red-600' : 'border-gray-300') . ' ' .
($disabledCondition ? 'bg-gray-100' : 'bg-white') . ' ' .
" focus:border focus:border-secondary-color h-45px block w-full rounded-md placeholder:text-paragraph-color placeholder:text-sm placeholder:text-opacity-60 $inputClass"
]) }}
>
@if($suffix)
<span class="absolute right-2 top-1/2 -translate-y-1/2 text-sm text-gray-700 bg-gray-100 px-2 py-0.5 rounded-md pointer-events-none">
{!! $suffix !!}
</span>
@endif
</div>
@error($name)
<p class="text-sm text-red-600 mt-1">{{ $message }}</p>
@enderror
</div>
This is how I call it in the form:
@if($type_id === 1)
<div class="md:col-span-3">
<x-numeric-mask-input name="price_sale" label="Price" wire:model.defer="price_sale" max="99999999999"
suffix="EUR" required />
@if($price_sale)
<p class="mt-2 text-sm text-gray-600 transition-opacity duration-300 ease-in-out">
Preview Price Format:
<strong>{{ \App\Services\Helper::formatPriceToList($price_sale) }}</strong>
</p>
@endif
</div>
@endif