Frage

I want my textbox in HTML page only accept number from 0 to 10, also accept: 0.5, 1.2, ... Thanks alot

War es hilfreich?

Lösung

Try this

<script>
function checkfloat(e,field){
     if (!(((e.keyCode>=48)&&(e.keyCode<=57))||(e.keyCode==46)))
     {
        e.keyCode=0;                   
     }     
 if (e.keyCode==46)
 {
    var patt1=new RegExp("\\.");        
    var ch =patt1.exec(field);       
    if(ch==".")
    {
        e.keyCode=0;
    }                        
 }
} 
</script>
<input type="text" onkeypress="checkfloat(event, this.value)">

Andere Tipps

You can use Regex for doing that!

The HTML5 number input type can do this:

<input type="number" min="0" max="10" />

However browser support for this is still poor. Only Chrome, Safari and Opera support this at this point in time.

Give it a test in Chrome though.

Demo

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top