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.
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
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()));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With