Excel currency format in HTML input
by vincentpace
HTML
<span class="input">
<input type="text" value="-">
<input type="number" class="hidden">
</span><br>
<span class="input">
<input type="text" value="-">
<input type="number" class="hidden">
</span>
CSS
input {
text-align:right;
width:10em;
/* box-sizing keeps width fixed when adding padding (http://stackoverflow.com/a/9484932/1652620) */
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
.input [type='text'] {
background-color:yellow;
padding-right:14px; /* line up with number text */
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
.input [type='number'] {background-color:orange;}
.hidden {display:none;}
.negative {color:red;}
/* Formatting to add $ sign (http://stackoverflow.com/q/8222528/1652620) */
.input {position: relative;}
.currency_symbol {
font-size:0.6em;
position:absolute;
top:7px;
left:5px;
}
.currency_symbol::before {content:"$"}
JavaScript
$(document).ready(function(){
$('.input [type="text"]').on('focus', function(){
$(this).next().removeClass().focus();
$(this).addClass('hidden');
});
$('.input [type="number"]').on('blur', function(){
var number = Math.round($(this).val() * 100) / 100;
var text = number.toFixed().toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
if (number < 0) {
$(this).prev().addClass('negative');
text = "("+text.replace(/-/g,"")+")";
}
if (!number) {text = "-";}
$(this).prev().val(text);
$(this).prev().removeClass();
$(this).addClass('hidden');
});
});