首页 > 解决方案 > 当数字输入字段中有点或逗号时,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()
);
})

标签: javascriptjquery

解决方案


您可以使用pattern输入标签的属性

^\d+$
  • ^- 字符串的开始
  • \d+- 一次或多次匹配任何数字
  • $- 字符串结束

 <br> <br>
 <form>
<input type="number" name="firstInput" value="" pattern="^\d+$">
<button type='submit'>Submit</button>

<pre class="result"></pre>


推荐阅读