我正在制作一个简单的网络应用程序。在它的一部分,我包含了一个 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);
});
Here是一把 fiddle 。
同样支持 float :
// 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);
});
和here是另一个 fiddle 。
更新:虽然您可能不需要这个,但这里有一个允许前导减号的解决方案。
// 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);
});
现在是只允许有效小数(包括 float 和负数)的最终解决方案:
// 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);
});
关于html - 在 <input type ="number"> 中禁用文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21215049/