jQuery Input Numeric Only

Selamat pagi semuanya ๐Ÿ™‚

Sebenernya masih bingung mau posting apaan, akhirnya kuputuskan untuk sharing mengenai input numeric only pada suatu textbox, jadi intinya bagaimana saat kita ketik di suatu textbox, hanya input angka yang diterima, untuk inputa huruf dan karakter lainnya tidak bisa. Saya sudah pernah posting mengenai hal yang sama di http://rendramm2.wordpress.com/2009/10/16/input-numeric-only/, cuman yang ini pake framework jQuery, yang dulu hanya pake javascript biasa.

Kenapa kok posting lagi, toh sama2 javascriptnya? Jawabannya adalah untuk opsi yang lebih advance dan lebih compatible :D, script berikut ini saya dapatkan dari http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery

Oke, berikut adalah source codenya :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$(document).ready(function(){
$("input[name='handphone']").keydown(function(event) {
// Allow: backspace, delete, tab and escape
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}else{
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
});
$(document).ready(function(){ $("input[name='handphone']").keydown(function(event) { // Allow: backspace, delete, tab and escape if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || // Allow: Ctrl+A (event.keyCode == 65 && event.ctrlKey === true) || // Allow: home, end, left, right (event.keyCode >= 35 && event.keyCode <= 39)) { // let it happen, don't do anything return; }else{ // Ensure that it is a number and stop the keypress if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) { event.preventDefault(); } } }); });
$(document).ready(function(){
	$("input[name='handphone']").keydown(function(event) {
		// Allow: backspace, delete, tab and escape
		if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
			// Allow: Ctrl+A
			(event.keyCode == 65 && event.ctrlKey === true) ||
			// Allow: home, end, left, right
			(event.keyCode >= 35 && event.keyCode <= 39)) {
				// let it happen, don't do anything
				return;
        }else{
			// Ensure that it is a number and stop the keypress
			if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
				event.preventDefault();
			}
		}
	});
});

Leave a Reply