0

I have the following html.

<input type="text" id="Price">

When the user enters a price amount in this input field,that should be automatically converted to a valid price format.

suppose a user enters 9200000,it should be automatically converted to 9,200,000.

So can anyboby explain how it can be done in javascript ?

It should be done in the keyDown,keypress or keyup events of this field.

Thanks

user2826169
  • 285
  • 3
  • 7
  • 16
  • [What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – thefourtheye Oct 08 '13 at 09:28
  • I have searched it on SO,but everywhere, I found just validations for it. I dont need validation.I need to convert it automatically to a price format if the entered value is not a valid price. – user2826169 Oct 08 '13 at 09:31
  • Did you look into http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript – Ajith S Oct 08 '13 at 09:36

3 Answers3

1

You can try this, I have used function in reference

 //Attach event
var el = document.getElementById("Price");
el.onkeydown = function(evt) {
    evt = evt || window.event;
    this.value = addCommas(stripNonNumeric(this.value));
};

// This function removes non-numeric characters
function stripNonNumeric( str )
{
  str += '';
  var rgx = /^\d|\.|-$/;
  var out = '';
  for( var i = 0; i < str.length; i++ )
  {
    if( rgx.test( str.charAt(i) ) ){
      if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
             ( str.charAt(i) == '-' && out.length != 0 ) ) ){
        out += str.charAt(i);
      }
    }
  }
  return out;
}

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

Working Demo

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

This is from How can I format numbers as money in JavaScript?

Number.prototype.formatMoney = function(c, d, t){
var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "." : d, 
    t = t == undefined ? "," : t, 
    s = n < 0 ? "-" : "", 
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
    j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };
alert((123456789.12345).formatMoney(2, '.', ','));
Community
  • 1
  • 1
Ajith S
  • 2,907
  • 1
  • 18
  • 30
0

Add an event listener on the input and write a function to insert the commas into your input value which the listener calls when you get a keyDown event.

dijipiji
  • 3,063
  • 1
  • 26
  • 21