nam nam - 2 months ago 10
jQuery Question

Jquery not removing commas and dollar symbols from number

In my ASP.NET MVC Core project, in the following

View
I'm using jquery to try to remove $ symbol and commas from the SaleAmount input tag before the form is submitted. But it's not doing anything. When I put alert('Test') inside the myJSFunction(), the alert successfully pops up that means the function is called but it's code for removing commas and $ is not working.

Model:

public class SaleViewModel
{
[DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
public float? SaleAmount { get; set; }
....
}


Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateSales(List<SaleViewModel> model, string returnUrl = null)
{
....
}


View:

@model IList<MyProj.Models.SaleViewModel>
....
<form id="target" asp-controller="DbRelated" asp-action="UpdateSales" asp-route-returnurl="@ViewData[" ReturnUrl"]" method="post" onsubmit="myJsFunction()">
<table class="table">
<thead>
....
</thead>
<tbody>
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>@Html.EditorFor(r => r[i].SaleAmount, new { htmlAttributes = new { @class = "saleAmt" } })</td>
....
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-default">Save</button>
</form>

@section scripts
{
<script>
$(function () {
$("#target").submit(function (event) {
event.preventDefault();
myJsFunction();
});
});
function myJsFunction() {
parseFloat($('.saleAmt').val().replace(/,/g, '').replace(/$/g, ''));
return false;
}
</script>
}

Answer

Your code does not update the values of your textboxes with the modified text. And in any case, your cancelling the submit so nothing will be posted. You can use

$("#target").submit(function () {
    var textboxes = $('.saleAmt');
    $.each(textboxes, function(index, item) {
        var text = $(this).val().replace(/[$,]/g, ''); // remove characters
        $(this).val(text); // update value
    });
});

Side note, there is no need to use parseFloat()