Hi Everyone,

How to write a javascript method that can check the value that user key in?

Example i create a textbox and user can only key in 0 - 50 to the textbox

Try this

<script type="text/javascript"> 
function validate() {            
    var FieldVal = document.getElementById('FieldName').value;                 
    if(FieldVal < 51) {           
        alert("Valid!");         
    } else {             
        alert("Invalid");     
    } 
}
</script>      
<input id="FieldName" type="text" name="MyField" onKeyUp="validate()" MaxLength="2" />

Hi Thanks for the code.. How to disable user to enter the value that are more than 50? is it possible?

Try this

<script type="text/javascript"> 
function validate() {            
    var FieldVal = document.getElementById('FieldName').value;                 
    if(FieldVal < 51) {           
        alert("Valid!");         
    } else {             
        alert("Invalid");     
    } 
}
</script>      
<input id="FieldName" type="text" name="MyField" onKeyUp="validate()" MaxLength="2" />

Hello,
well you can try this. Im at work so i cant test it, but try this.

if(FieldVal > 50) {
document.getElemenyById('FieldName').value = '';
}

Try this, based on fobos' post :

onload = function(){
    var field = document.getElementById('myField');
	field.onkeyup = function(){
		var val = parseInt(this.value);
		this.value = (!val) ? '' : Math.min(50,val);
	}
}
<input type="text" id="myField" name="myField" maxlength="2" />

Use: <!doctype native> and
try this -it might even work.

field.onpropertychange=//when perfection comes to play
field.onkeyup=
function(v){this.value=(v=Number(this.value))?v>50?50:v:""};

<input id=field ...> Regards

Thank everyone for the great solutions =)

Thank everyone for the great solutions =)

Here is my other question related to same question

I want only 2 digits after decimal point like

#######.99

If user enter #######.999 then it must return false.

No you don't want that, (not on this thread); -because, it is only vaguely related to this one. Regarding javascript it requires a totally different solution which makes it a completely different question/problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.