< input type =" number">中禁用文本输入 [英] Disable Text Entry in <input type="number">

查看:72
本文介绍了< 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);
});

最后的小提琴

这篇关于&lt; input type =&quot; number&quot;&gt;中禁用文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆