2013-04-04 22 views
-1

我有一個數字類型的輸入框。我需要的是限制用戶輸入小數點後不超過6位數字。我搜查了一些,但我得到的是maxstep財產。有沒有可能使用任何HTML屬性?將與JavaScript解決方案,以及html解決方案將是可取的。如何限制用戶輸入6位數字後使用html/javascript

+0

你將不得不使用Javascript ...純html解決方案是提供兩個輸入框之間的中間點,並將第二個框限制爲6個字符 – jsshah 2013-04-04 06:42:42

+0

嘗試處理輸入框按鍵事件by javascript – 2013-04-04 06:43:46

+1

http://stackoverflow.com/questions/1830626/restricting-a-用戶輸入多於7位數字前decimel和3後dechl – Kasnady 2013-04-04 06:46:16

回答

2

有了今天的HTML支持,在我們有the pattern attribute之前,你不能沒有JavaScript。

這裏是一個基於JavaScript的解決方案防止任何錯誤的輸入:

var lastValue=''; 
yourinput.onkeyup = function(e) { 
    if (!/^\d*\.?\d{0,6}$/.test(this.value)){ 
    this.value = lastValue; 
    } 
    lastValue = this.value; 
} 

Demonstration

而不是防止輸入,你也可以簡單地顯示一個消息:

<input id=yourinput pattern="\d+"> 
<span id=bad style="display:none;color:red">BAD</span> 


document.getElementById('yourinput').onkeyup = function(e) { 
    document.getElementById('bad').style.display = 
    /^\d*\.?\d{0,6}$/.test(this.value) ? 'none' : 'block'; 
} 

Demonstration

+0

+1顯示超出限制的錯誤消息,但我很好防止用戶在小數點後輸入6位以上的數字。 – 2013-04-04 06:58:26