繁体   English   中英

当数字输入字段中包含点或逗号时,jQuery val()返回空字符串

[英]jQuery val() returns empty string for number input fields when they have dot or comma in them

认为这取决于您操作系统中的数字设置。 但是:对我来说,我可以输入点. 输入字段。 对于我的应用程序,这是不希望的。 我想禁用小数,以及所有不是数字的内容

另外,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> 

Try to change the above html input element type="number" --> type="text"
<input type="number" name="firstInput" value="....">
<input type="text" name="firstInput" value="....">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM