我正在制作一个简单的网络应用程序。在其中一部分,我添加了一个 type="number"
的输入框<input type="number" min="0">
无论如何,当我在最新的 Google Chrome 浏览器中运行代码时,我也可以输入文本了:
我不希望用户能够这样做。我该如何纠正这个问题?
您可以使用 JavaScript(例如使用 jQuery)仅允许特定字符:
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^0-9]/g, '');
// Update value
$(this).val(sanitized);
});
这里是一把小提琴。
与支持浮动相同:
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^0-9.]/g, '');
// Remove the first point if there is more than one
sanitized = sanitized.replace(/\.(?=.*\.)/, '');
// Update value
$(this).val(sanitized);
});
而这里是另一个小提琴。
更新:虽然您可能不需要这个,但这里有一个允许前导减号的解决方案。
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^-0-9]/g, '');
// Remove non-leading minus signs
sanitized = sanitized.replace(/(.)-+/g, '$1');
// Update value
$(this).val(sanitized);
});
现在的最终解决方案仅允许有效小数(包括浮点数和负数):
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^-.0-9]/g, '');
// Remove non-leading minus signs
sanitized = sanitized.replace(/(.)-+/g, '$1');
// Remove the first point if there is more than one
sanitized = sanitized.replace(/\.(?=.*\.)/g, '');
// Update value
$(this).val(sanitized);
});
您可以使用 HTML5 输入类型数字 来限制仅输入数字:
<input type="number" name="someid" />
这仅适用于兼容 HTML5 的浏览器。确保您的 html 文档的文档类型是:
<!DOCTYPE html>
对于一般用途,您可以进行如下 JS 验证:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="someid" name="number" onkeypress="return isNumberKey(event)"/>
如果您想允许小数,请将“if条件”替换为:
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
只需添加 onkeydown="return false" 即可。
<input type="number" min="0" onkeydown="return false">