簡體   English   中英

只允許使用javascript和mootools將整數和浮點數輸入字段

[英]Only allowing ints and floats to be entered into field with javascript and mootools

我需要某種關於如何只允許將int或float輸入到表單輸入字段中的指示。 驗證必須在按鍵事件上進行。 我遇到的問題是,例如在輸入1.2時,keyup事件函數中的檢查會看到1.這不是數字。

這是我的代碼:

document.id('inputheight').addEvent('keyup', function(e) {
    this.value = this.value.toFloat();
    if (this.value == 'NaN') {
        this.value = 0;
    }         
});

任何幫助表示贊賞!

您可以簡單地清理keyup字段的值。 這樣的事情應該可以解決問題:

this.value = this.value.replace(/([^\d.]+)?((\d*\.?\d*)(.*)?$)/, "$3");

正則表達式立即用遇到的第一個數字字符串替換該值。

([^\d.]+)?  // optionally matches anything which is not
            // a number or decimal point at the beginning

(\d*\.?\d*) // tentatively match any integer or float number

(.*)?$      // optionally match any character following
            // the decimal number until the end of the string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM