Set numbers allow only feature to multiple textboxes – jQuery

Standard

Below code snippets allows developer to register all textboxes with non-decimal numbers allow only feature at the load of DOM.

function allowNumberOnly(textboxId) {
    $('#' + textboxId).on("keypress", function (event) {
        $(this).val($(this).val().replace(/[^0-9\.]/g, ''));
        if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37
            || event.keyCode == 39) {
            return true;
        }
      else if ((event.which < 48 || event.which > 57) && (event.which != 8)){
            event.preventDefault();
        } else return true;
    });
}

Example:

$(document).ready(function () {
      allowNumberOnly('txtUserAge');
      allowNumberOnly('txtUserId');
});

P.S. This function allows the working of delete/backspace and right/left movement keys in textbox.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s