I have a textbox to get user input amount of money, so I want a dot (.) will always be added in front of the last 2 digits automatically as soon as user started to type in the textbox (not after they finished typing but on the go).
For example:
- User moved the mouse to the textbox and typed '1' => textbox is automatically displaying as 0.01
- User typed '12' => textbox displaying as 0.12
- User typed '123' => textbox displaying as 1.23
- User typed '1234' => textbox displaying as 12.24
- User typed '123456' => textbox displaying as 1234.56 and so on...
So the textbox will always be 2 decimal places. My JS is really lacking now (I am trying to improve it) I know the logic is really not hard but I am having difficulties with JS syntax and functions. I also tried the Ajax toolkit Masked Edit Extender but there is a bug with ASP.NET 4.5 (where the mask not go away if textbox lost focus)
My existing code (helped by Azim) only add a dot and 00 at the end of the number and after people move the mouse away (textbox lost focus), I really need help here. (I already have a JS filter so that user can only type in digits, nothing else allowed)
<!-- BEGIN Add dot (.) to the end of amount -->
<script type="text/javascript">
function AppendDot(textbox) {
var text = textbox.value;
document.getElementById("<%=txtAmount.ClientID %>").value = "";
if (text.indexOf(".") == -1) {
document.getElementById("<%=txtAmount.ClientID %>").value = text + ".00";
}
else {
document.getElementById("<%=txtAmount.ClientID %>").value = text;
}
}
</script>
<!-- END Add dot (.) to the end of amount -->
<asp:TextBox ID="txtAmount" runat="server" MaxLength="12" onchange="AppendDot(this);" />