16

I am using lots of HTML 5 input controls in my pages. One of my requirement is to have a textbox with currency feature. For this i tried this:

<input type="number" pattern="(d{3})([.])(d{2})" />

This allows me to type values like 10,000.00

But still all its not meeting all my requirements. I want that if the user types in 10000 it should convert it to currency format like 10,000 onblur.

And when i read the value from the input type in my Javascript, it should give me a float instead of a string value which i cannot use to calculate without parsing.

gherkins
  • 14,603
  • 6
  • 44
  • 70
user2561997
  • 443
  • 1
  • 6
  • 18
  • `input type="number".value` will be a string in any case. You need to parse it at some point anyway... – Teemu Aug 19 '13 at 08:02
  • input type="number".value will be string in any case. but simple having parseFloat(input type="number".value) would have worked in all cases. – user2561997 Aug 19 '13 at 08:09

2 Answers2

27

Here's a workaround with an additional input type="text":

http://jsfiddle.net/UEVv6/2/

HTML

<input type="text" id="userinput" pattern="[0-9]*">
<br>
<input type="number" id="number">

JS

document.getElementById("userinput").onblur =function (){    

    //number-format the user input
    this.value = parseFloat(this.value.replace(/,/g, ""))
                    .toFixed(2)
                    .toString()
                    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    //set the numeric value to a number input
    document.getElementById("number").value = this.value.replace(/,/g, "")

}

regex is from here How to print a number with commas as thousands separators in JavaScript

Community
  • 1
  • 1
gherkins
  • 14,603
  • 6
  • 44
  • 70
2

try this - http://jsbin.com/azOSayA/1/edit

function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
    }
    return val;
  }
$('#elementID').focusout(function(){

  alert(commaSeparateNumber($(this).val()));
});
Amith
  • 1,424
  • 1
  • 10
  • 22