How to mask input fields in Jquery?

Setu Kumar Basak
2 min readJul 4, 2018

This is my first post at medium. Trying to get hands on here. From now on, I will post my findings at medium. Today, I will start with masking input field in Jquery.

Few days back, I had to convert previously used Telerik’s RadNumericTextBox to simple html input field and I had to apply the same masking to the input field just like the RadNumericTextBox.

<telerik:RadNumericTextBox ID="txtNewAmt" runat="server" EnableViewState="false"
Width="100px" CssClass="input" Type="Number" EnabledStyle-HorizontalAlign="Right"
PlacesBeforeDecimal="11" NumberFormat-DecimalDigits="2">
<ClientEvents OnKeyPress="validateRegExMaskNumeric" />
</telerik:RadNumericTextBox>

Here, in the input,

  1. Only numbers are allowed.
  2. Numbers will be aligned from right.
  3. Places before decimal can be 11 or less and after decimal can be 2 or less.

So, I searched for existing plugins in Jquery and i found two plugins worth noting. One is jQuery Mask Plugin and Mavrin MaskInput Plugin. jQuery Mask Plguin is bulkier than MaskInput as it contains more features. But, for my need, I chose MaskInput Plugin.

So, let’s start coding. At first, download the plugin file from here and include it in the html file.

<script src="jquery.numberMask.js"></script>

One thing to note here is that include the plugin file after the jquery has been loaded for the page. It’s better to load the file just before the end of the body tag.

Suppose, I have simple input box like below in the html file:

<input type='text' id='txtAmt' class='text-right'/>

To write the text right aligned, let’s include text-right class in css file.

.text-right {   text-align: right;}

Now, let’s include below code snippet to initialize the input field for masking.

$(document).ready(function () {    $('#txtAmt').numberMask({ type: 'float', beforePoint: 11, afterPoint: 2, decimalMark: '.', defaultValueInput: '' });});

That’s it. The input field will now automatically mask the input. This plugin is very light and easy to use but it lacks one feature. Suppose, I want to set the value of the input field dynamically like below:

$('#txtAmt').val('7.2000345678')

The input field will show the value 7.2000345678. But, it should mask the value to 7.20. But, the plugin does not provide any functionality for that. So, I extended the plugin to do that. You can download this version of plugin from here.

Now, whenever you set value dynamically to the input field, need to trigger the masking again like below:

$('#txtAmt').val('7.2000345678').trigger('maskInput');

Now, the output will be 7.20 in the input field.

That’s it for today. Bye Bye :) :).

--

--