問題描述
我需要確保某個(gè) <input>
字段僅將數(shù)字作為值.輸入不是表單的一部分.因此它不會被提交,因此在提交期間進(jìn)行驗(yàn)證不是一種選擇.我希望用戶不能輸入除數(shù)字以外的任何字符.
有沒有一種巧妙的方法來實(shí)現(xiàn)這一點(diǎn)?
HTML 5
您可以使用 HTML5 輸入類型編號 僅限制數(shù)字條目:
這僅適用于 HTML5 投訴瀏覽器.確保您的 html 文檔的 doctype 是:
<!DOCTYPE html>
另請參閱 https://github.com/jonstipe/number-polyfill 以獲得透明支持在舊版瀏覽器中.
JavaScript
更新:有一個(gè)新的非常簡單的解決方案:
<塊引用>它允許您在文本 <input>
上使用 任何 類型的輸入過濾器,包括各種數(shù)字過濾器.這將正確處理復(fù)制+粘貼、拖放、鍵盤快捷鍵、上下文菜單操作、不可鍵入的鍵和所有鍵盤布局.
請參閱此答案或自己嘗試在 JSFiddle 上.
出于一般目的,您可以進(jìn)行 JS 驗(yàn)證,如下所示:
function isNumberKey(evt){var charCode = (evt.which) ?evt.which : evt.keyCodeif (charCode > 31 && (charCode < 48 || charCode > 57))返回假;返回真;}<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>
如果您想允許小數(shù),請將if 條件"替換為:
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
來源:HTML文本輸入只允許數(shù)字輸入p>
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 5
You 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.
JavaScript
Update: There is a new and very simple solution for this:
It allows you to use any kind of input filter on a text
<input>
, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.
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 input
JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/
這篇關(guān)于如何使 HTML 輸入標(biāo)簽只接受數(shù)值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!