Alpine JS

Follow

Alpine JS

Follow

Replacing oninput with x-mask

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

Anjanesh Lekshminarayanan's photo
Anjanesh Lekshminarayanan
·Nov 30, 2022·

1 min read

<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)"
/>
 
Share this