2013-04-04 46 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

相关问题