javascript - 当数字输入字段中有点或逗号时,jQuery val() 返回空字符串
问题描述
我认为这取决于您的操作系统中的数字设置。但是:对我来说,我可以.
在输入字段中输入点。对于我的应用程序来说,这是不希望的。我想禁用小数,以及所有不是数字的东西
作为奖励,jquery 不会检测数字字段中的点
https://codepen.io/jossnaz/pen/dLMmoQ
看起来像这样:
HTML:
Please type into the first input box some dots . then click out of the input box to trigger the change event <br> <br>
<input type="number" name="firstInput" value="....">
<input type="number" name="second" value="5">
<pre class="result"></pre>
Javascript:
$('input').on('change', function(){
$('.result').html(
'First input val: ' + $('input').first().val() + "<br/>" + "Second input val: "
+ $('input').last().val()
);
})
解决方案
您可以使用pattern
输入标签的属性
^\d+$
^
- 字符串的开始\d+
- 一次或多次匹配任何数字$
- 字符串结束
<br> <br>
<form>
<input type="number" name="firstInput" value="" pattern="^\d+$">
<button type='submit'>Submit</button>
<pre class="result"></pre>
推荐阅读
- d3.js - d3折线图中显示的随机水平线?
- javascript - 将新的 SerialPort 声明为变量不允许我读取数据?串口节点js
- c# - 是否有我实现自定义方法的属性的简写?
- ios - 导航栏前的 SwiftUI 视图
- django - 错误:(1062,“重复条目 'search-laft_cadaveres_cni_identificados' 键 'django_content_type_app_label_model_76bd3d3b_uniq'”)
- mongodb - Mongo DB maxScan - 无法识别的字段
- c# - Blazor WebAssembly:设置不同的 CurrentUICulture 和 CurrentCulture 时无法加载本地化字符串
- testing - 使用 Mocha/Chai 测试对象数组是否包含某个键
- android - 在没有 Root 和 ADB 的情况下自动执行 Android 任务
- python - 在 32 位和 64 位 Python 中导入 PIL(枕头)时出错