Home > Technical > Decimal TextBox with jQuery

Decimal TextBox with jQuery

Problem : I had to work with formatting decimal places for a quantity text box (or label) on a halfway developed project.  I wanted a solution, where i can handle this on one place and applies everywhere with quantity text box.

Solution :

1. Placed this code on the master page, This section will

  • Format all the textboxes content with specific css (QuantityTextBox in this example) on page load,
  • allow to enter only numeric values with one decimal mark. (onkeydown, will call the js function called OnlyDecimalNumbers).
  • after entering the data, input will format on leave (on onblur event)

 var decimalPoints = Number(‘<%: DecimalPoints%>’); //getting number of decimal points from serverside, which user can //defines

$(“.QuantityTextBox”).each(function () {
var originalText = Number($(this).val());

$(“.QuantityTextBox”).live(“keydown”, function (event) {
return OnlyDecimalNumbers(event, $(this));

$(“.QuantityTextBox”).live(“blur”, function () {
var stringValue = $(this).val();
var lastChar = stringValue[stringValue.length – 1];
if (lastChar == ‘.’) {
stringValue = stringValue.slice(0, stringValue.length – 1);

var originalText = Number(stringValue);

2. Added following function on JS file.

//common function to use for allowing only numbers with decimal places. call on onkeydown
function OnlyDecimalNumbers(event, control) {
var existingValue = control.val();
var charCode = (event.which) ? event.which : event.keyCode;

if (event.shiftKey)
return false;

if (charCode == 46 || charCode == 8)
return true;

if (existingValue.indexOf(“.”) == -1 && charCode == 190)
return true;

if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;

return true;

3.  Finally add “QuantityTexBox” css on all the quantity showing/adding textboxes.

Pros on this solution : Can handle all the quantity related formatting on one place, if we have added above css on all the qty textboxes.

Cons : If we need to different CSS per textboxes for styles, we cannot do this, on my situation we were not adding styles directly to textboxes.

  1. No comments yet.
  1. No trackbacks yet.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s