javascript - 设置文本框接受 2 位小数

标签 javascript jquery asp.net-mvc html.textboxfor

我有这两个文本框,我需要它们只允许输入小数点后两位。 我假设 jQuery 或 Javascript 事件可以做到这一点。我只是不确定如何在 Javascript 中调用文本框。 任何帮助将不胜感激

@Html.TextBoxFor(m => Model.Categories[c].EstimateGroups[g].EstimateItems[i].PerUnitCost,
                 new { @disabled = "disabled", @onchange = "costUpdate(this);", @cstType = "perUnit",@id="perUnit"})

<span class="sideLabel">@Model.Categories[c].EstimateGroups[g].EstimateItems[i].PerUnitDescription</span>

if (Model.Categories[c].EstimateGroups[g].EstimateItems[i].Units != null
 && !Model.Categories[c].EstimateGroups[g].EstimateItems[i].IsBasedOnHomeSquareFootage)
{ 
    @Html.TextBoxFor(m => Model.Categories[c].EstimateGroups[g].EstimateItems[i].Units,
                     new { @disabled = "disabled", @onchange = "costUpdate(this);", @cstType = "units" })
}

最佳答案

您可以使用RegularExpression属性。这将完成这项工作。

[RegularExpression(@"^\d+.\d{0,2}$", 
             ErrorMessage = "It cannot have more than one decimal point value")]
public double PerUnitCost {get;set;}   

这里在{0,2}中,0和2表示小数点后的最小和最大位数。所以根据您的要求进行更改。

关于javascript - 设置文本框接受 2 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18235111/

相关文章:

javascript - 解析 : ParseError { code: 101, 消息: 'Object not found.' }

javascript - 复选框值的总和

javascript - Knockout 组件 - 从子 ViewModel 动态应用绑定(bind)

javascript - 增加/减少滚动上的元素填充

javascript - facebook/twitter 分享按钮如何避免被弹出窗口拦截器拦截?

asp.net-mvc - ASP.NET MVC 数据注释工具提示

asp.net-mvc - MVC ASP.NET 没有为此对象定义无参数构造函数

c# - 从局部 View 设置主 url 的路由值

Javascript 随机数显示

javascript - 如何只更改 DOM 元素中的文本而不替换任何子元素