nam nam - 2 months ago 14
Javascript Question

ASP.NET MVC 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 AnnualGrant
{
[Key]
public int Sale_Id { get; set; }

public int? FiscalYear { get; set; }

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

public int StateId { get; set; }
public StateName StateName { get; set; }
}


Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateSales(List<SaleViewModel> model, string returnUrl = null)
{
if (ModelState.IsValid)
{
foreach (var item in model)
{
var oAnnualSales = _context.AnnualSales.Where(r => r.StateId.Equals(item.StateId)).FirstOrDefault();
if (oAnnualSales != null)
{
oAnnualSales.FiscalYear = item.FY;
oAnnualSales.SaleAmount = item.SaleAmount;
}
else
{
AnnualSale oAnnualSaleNew = new AnnualSale { StateId = item.StateId, FiscalYear = item.FY, SaleAmount = item.SaleAmount};
_context.Add(oAnnualSaleNew);
}
}
await _context.SaveChangesAsync();
return View(model);
}

// If we got this far, something failed, redisplay form
return View();
}


View:

public class AnnualSale
{ @model IList<MyProj.Models.SaleViewModel>
<div class="row">
<div class="col-md-9">
<form id="target" asp-controller="DbRelated" asp-action="UpdateSales" asp-route-returnurl="@ViewData[" ReturnUrl"]" method="post" onsubmit="myJsFunction()">
<table class="table">
<thead>
<tr>
<th></th>
<th>
State Name
</th>
<th>
Sale Amount
</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>@Html.HiddenFor(r => r[i].StateId)</td>
<td>
@Html.EditorFor(r => r[i].StateName)
</td>
<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>
</div>
</div>
}
@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()