我有一个<input type="number">,我想将用户的输入限制为纯数字或带有小数点后最多2位的数字。
基本上,我是在要求一个价格输入。
我想避免使用正则表达式。有办法吗?
<input type="number" required name="price" min="0" value="0" step="any">
我有一个<input type="number">,我想将用户的输入限制为纯数字或带有小数点后最多2位的数字。
基本上,我是在要求一个价格输入。
我想避免使用正则表达式。有办法吗?
<input type="number" required name="price" min="0" value="0" step="any">
当前回答
输入:
step="any"
class="two-decimals"
脚本:
$(".two-decimals").change(function(){
this.value = parseFloat(this.value).toFixed(2);
});
其他回答
使用step="而不是step="any",因为它允许小数位数任意。“01”,最多允许小数点后两位。
更多详细信息见规范:https://www.w3.org/TR/html/sec-forms.html#the-step-attribute
输入:
<input type="number" name="price" id="price" required>
脚本:
$('#price').on('change', function() {
var get_price = document.getElementById('price').value;
var set_price = parseFloat(get_price).toFixed(2);
$('input[name=price').val(set_price);
})
使用这段代码
<input type="number" step="0.01" name="amount" placeholder="0.00">
HTML5 Input元素的默认Step值为Step ="1"。
使用Javascript在文本框中只输入3个小数点。
<input type="text" class="form-control" onkeypress='return AllowOnlyAmountAndDot(this,event,true);/>
function AllowOnlyAmountAndDot(id, e, decimalbool) {
if(decimalbool == true) {
var t = id.value;
var arr = t.split(".");
var lastVal = arr.pop();
var arr2 = lastVal.split('');
if (arr2.length > '2') {
e.preventDefault();
}
}
}
我发现使用jQuery是我最好的解决方案。
$( "#my_number_field" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});