Good day to all,
I just started developing a program in MVC (very newbie in both MVC and JQuery). In my front-end, I need to add two textbox and show the result in the 3rd textbox. Below is my JQuery code:
- function Comma(Num) {
- Num += '';
- Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
- Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
- x = Num.split('.');
- x1 = x[0];
- x2 = x.length > 1 ? '.' + x[1] : '';
- var rgx = /(\d+)(\d{3})/;
- while (rgx.test(x1))
- x1 = x1.replace(rgx, '$1' + ',' + '$2');
- return x1 + x2;
- }
-
- $(function () {
-
- var total_amount = function () {
- var sum = 0;
- $('.amount').each(function () {
- var num = $(this).val().replace(',', '');
- if (num != 0) {
- sum += parseFloat(num);
- }
- });
- $('#total_amount').val(sum);
- }
-
-
- $('.amount').keyup(function () {
- total_amount();
- });
- });
Below is my mark-up also:
- @Html.LabelFor(model => model.laborCost, htmlAttributes: new { @class = "control-label col-md-1" })
- <div class="col-md-2">
- @Html.EditorFor(model => model.laborCost, new { htmlAttributes = new { @class = "form-control text-right amount", @onkeyup = "javascript:this.value=Comma(this.value);" } })
- @Html.ValidationMessageFor(model => model.laborCost, "", new { @class = "text-danger" })
- </div>
- @Html.LabelFor(model => model.partsCost, htmlAttributes: new { @class = "control-label col-md-1" })
- <div class="col-md-2">
- @Html.EditorFor(model => model.partsCost, new { htmlAttributes = new { @class = "form-control text-right amount", @onkeyup = "javascript:this.value=Comma(this.value);" } })
- @Html.ValidationMessageFor(model => model.partsCost, "", new { @class = "text-danger" })
- </div>
- <div class="col-sm-1">
- <b>
- Total
- </b>
- </div>
- <div class="col-sm-2">
- <input type="text" name="totalCost" class="form-control text-right" readonly="readonly" value="0" id="total_amount" />
- </div>
My problem is that, whenever the number goes more than 6 0's, the result is no long correct. see sample:
My country is Laos so transaction amount usually exceeds a million. Thanks a lot for any assistance.