< input type =" number">中禁用文本输入

问题描述:

我正在制作一个简单的网络应用程序。在它的一部分中,我已经包含了一个类型=number的输入框

I am making a simple web app. At one part of it, I have included an input box of type="number"

<input type="number" min="0">

无论如何,当我在最新的Google Chrome浏览器中运行代码时,我也可以输入文字:

Anyhow, when I run the code in my latest Google Chrome Browser, I am able to enter text too:

我不希望用户能够这样做。我应该如何解决这个问题?

I do not want users to be able to do that. How should I rectify this?

您可以使用JavaScript(例如jQuery)来仅允许特定字符:

You can use JavaScript (e.g. with jQuery) to allow only specific characters:

// 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);
});

这里是另一个小提琴。

更新:虽然你可能不需要这个,但这是一个解决方案,

Update: Although you might not need this, here is a solution that allows a leading minus sign.

// 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);
});

第三小提琴

现在最终的解决方案只允许有效的小数(包括浮点数和负数):

And now a final solution that allows only valid decimals (including floats and negative numbers):

// 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);
});

最后的小提琴