input number only

Allows number only

by Moien Tajik

HTML

<div class="price">
    <input type="text" class="numberOnly" autocomplete="off" maxlength="50" /><div>$</div>
</div>
<br><br>
<div class="price">
    <input type="text" class="numberOnly" autocomplete="off" maxlength="50" /><div>$</div>
</div>
<br><br>
<div class="price">
    <input type="text" class="numberOnly" autocomplete="off" maxlength="50" /><div>$</div>
</div>

CSS

body{
    margin:50px;
}

.price{
    display:inline-block;
    border:1px solid #ababab;
	-moz-border-radius:3px;
    -webkit-border-radius:3px;
    border-radius:3px;
}

.price > div{
    display:inline-block;
    padding:8px 8px 8px 0;
    font-size:14px;
    cursor:text;
    color:#666;
}

.price > input{
    width:200px;
    border:0;
    padding:8px 4px 8px 8px;
    margin:0;
    font-size:14px;
    color:#666;
    cursor:text;
    text-align:right;
    outline:none;
}

.price > input::-ms-clear{
    display: none;
}

JavaScript

$('.price > div').click(function(){
    $('.price > input:eq('+$('.price > div').index(this)+')').focus();
});

$('.numberOnly').on('keydown', function(e){
	
  if(this.selectionStart || this.selectionStart == 0){
	// selectionStart won't work in IE < 9
	
	var key = e.which;
	var prevDefault = true;
	
	var thouSep = " ";  // your seperator for thousands
	var deciSep = ",";  // your seperator for decimals
	var deciNumber = 2; // how many numbers after the comma
	
	var thouReg = new RegExp(thouSep,"g");
	var deciReg = new RegExp(deciSep,"g");
	
	function spaceCaretPos(val, cPos){
		/// get the right caret position without the spaces
		
		if(cPos > 0 && val.substring((cPos-1),cPos) == thouSep)
		cPos = cPos-1;
		
		if(val.substring(0,cPos).indexOf(thouSep) >= 0){
		cPos = cPos - val.substring(0,cPos).match(thouReg).length;
		}
		
		return cPos;
	}
	
	function spaceFormat(val, pos){
		/// add spaces for thousands
		
		if(val.indexOf(deciSep) >= 0){
			var comPos = val.indexOf(deciSep);
			var int = val.substring(0,comPos);
			var dec = val.substring(comPos);
		} else{
			var int = val;
			var dec = "";
		}
		var ret = [val, pos];
		
		if(int.length > 3){
			
			var newInt = "";
			var spaceIndex = int.length;
			
			while(spaceIndex > 3){
				spaceIndex = spaceIndex - 3;
				newInt = thouSep+int.substring(spaceIndex,spaceIndex+3)+newInt;
				if(pos > spaceIndex) pos++;
			}
			ret = [int.substring(0,spaceIndex) + newInt + dec, pos];
		}
		return ret;
	}
	
	$(this).on('keyup', function(ev){
		
		if(ev.which == 8){
			// reformat the thousands after backspace keyup
			
			var value = this.value;
			var caretPos = this.selectionStart;
			
			caretPos = spaceCaretPos(value, caretPos);
			value = value.replace(thouReg, '');
			
			var newValues = spaceFormat(value, caretPos);
			this.value = newValues[0];
			this.selectionStart = newValues[1];
			this.selectionEnd   = newValues[1];
		}
	});
	
	if((e.ctrlKey && (key == 65 || key == 67 || key == 86 || key == 88 || key == 89...