I have 4 fields which are money 1, 2, 3 and Total, when a value is placed within money 1, 2, 3 an automatic calculation occurs and it appears in the Total field. However when I click the edit link all 4 fields are still populated however they are displayed to 4 decimal places (i.e 15.1511) instead of two decimal places (i.e 15.15). I've seen examples where other people have hardcoded their values into javascript however as shown in my code below I don't have hardcoded numeric values.
<script type="text/javascript">
function sum() {
var txtFirstNumberValue = document.getElementById('money1').value;
var txtSecondNumberValue = document.getElementById('money2').value;
var txtThirdNumberValue = document.getElementById('money3').value;
var result = parseFloat(txtFirstNumberValue) + parseFloat(txtSecondNumberValue) + parseFloat(txtThirdNumberValue);
if (!isNaN(result)) {
document.getElementById('Total').value = result.toFixed(2);
}
}
</script>
My html View code is
@Html.LabelFor(model => model.Total, "Total", new { @class = "control-label col-md-5" })
<div class="col-md-offset-0">
<input type="text" id="Total" name="Total" value="@Model.Total" />
@Html.ValidationMessageFor(model => model.Total)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.money1, "money1", new { @class = "control-label col-md-5" })
<div class="col-md-offset-0">
<input type="text" id="money1" onkeyup="sum();" name="money1" value="@Model.money1" />
@Html.ValidationMessageFor(model => model.money1)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.money2, "money2", new { @class = "control-label col-md-5" })
<div class="col-md-offset-0">
<input type="text" id="money2" onkeyup="sum();" name="money2" value="@Model.money2" />
@Html.ValidationMessageFor(model => model.WeeklyRatesPayable)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.money3, "money3", new { @class = "control-label col-md-5" })
<div class="col-md-offset-0">
<input type="text" id="money3" onkeyup="sum();" name="money3" value="@Model.money3" />
@Html.ValidationMessageFor(model => model.money3)
</div>
</div>
Is there a way of achieving this with javascript or formatting the input element?