JSFiddle 演示:http://jsfiddle.net/viralpatel/nSjy7/I need to make sure that a certain <input> field only takes numbers as value.The input is not part of a form. Hence it doesn't get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.Is there a neat way to achieve this? 解决方案 HTML 5You can use HTML5 input type number to restrict only number entries:<input type="number" name="someid" />This will work only in HTML5 complaint browser. Make sure your html document's doctype is:<!DOCTYPE html>See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.JavaScriptUpdate: There is a new and very simple solution for this:See this answer or try it yourself on JSFiddle.For general purpose, you can have JS validation as below:function isNumberKey(evt){ var charCode = (evt.which) ? evt.which : evt.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true;}<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>If you want to allow decimals replace the "if condition" with this:if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))Source: HTML text input allow only numeric inputJSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/ 这篇关于如何让 HTML 输入标签只接受数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-11 14:46