Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML 5 Currency format [duplicate]

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.

like image 539
user2561997 Avatar asked Aug 19 '13 07:08

user2561997


2 Answers

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

like image 169
mgherkins Avatar answered Nov 19 '22 18:11

mgherkins


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()));
});
like image 27
Amith Avatar answered Nov 19 '22 20:11

Amith