Skip to main content

Command Palette

Search for a command to run...

Replacing oninput with x-mask

Add comma separator to numbers in text fields as an when you type

Updated
1 min read
A
I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in

<input type="text" pattern="[0-9,.]{0,10}"/>

Using the mask plugin we can achieve the comma separators inserted to the numbers in the text box instead of writing our own JavaScript.

Replace something like this we get from searching Google

oninput='this.value = this.value.replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")'

with this :

x-mask:dynamic="$money($input)"

Finally :

<!-- Alpine Plugins -->
<script defer src="https://unpkg.com/@alpinejs/mask@3.x.x/dist/cdn.min.js"></script>

<!-- Alpine Core -->
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

<input
    type="text"
    name="bid" 
    placeholder="Enter your bid amount"
    pattern="[0-9,.]{0,10}"
    x-mask:dynamic="$money($input)"
/>
M

and How to save the value of the masked model in the livewire component to the database. the x-mask:dynamic="$money($input)" is something like 99,100,200 but I need to save 99100200?

A

I haven't yet got into Livewire but you could do a replaceAll(',', '') on form submit - bad idea if it's repetitive.

Or

<script>
    Alpine.data('x-data', {
        get computedValue() {
            return this.myValue.replace(/,/g, '');
        }
    });
</script>

<span x-text="computedValue"></span>