Jquery limits text fields to Numbers integers and decimals

  • 2020-03-30 00:39:33
  • OfStack

 
$(function(){ 
//Text fields can only enter Numbers (not including decimals) and block input and paste
$.fn.integer= function() { 
$(this).css("ime-mode", "disabled"); 
this.bind("keypress",function(e) { 
var code = (e.keyCode ? e.keyCode : e.which); //Firefox IE compatible
if(!$.browser.msie&&(e.keyCode==0x8)){ //Backspace cannot be used in firefox
return ; 
} 
return code >= 48 && code<= 57; 
}); 
this.bind("paste", function() { 
return false; 
}); 
this.bind("keyup", function() { 
if (/(^0+)/.test(this.value)) { 
this.value = this.value.replace(/^0*/, ''); 
} 
}); 
}; 

//Text boxes can only enter Numbers (including decimals) and block input and paste
$.fn.number= function() { 
$(this).css("ime-mode", "disabled"); 
this.bind("keypress",function(e) { 
var code = (e.keyCode ? e.keyCode : e.which); //Firefox IE compatible
if(!$.browser.msie&&(e.keyCode==0x8)){ //Backspace cannot be used in firefox
return ; 
} 
if(this.value.indexOf(".")==-1){ 
return (code >= 48 && code<= 57)||(code==46); 
}else{ 
return code >= 48 && code<= 57 
} 
}); 
this.bind("paste", function() { 
return false; 
}); 
this.bind("keyup", function() { 
if(this.value.slice(0,1) == "."){ 
this.value = ""; 
} 
}); 
this.bind("blur",function(){ 
if(this.value.slice(-1) == "."){ 
this.value = this.value.slice(0,this.value.length-1); 
} 
}); 
}; 
}); 

Related articles: