Somente Números em Jquery

Posted on : by : admin

Exemplo 1

$(‘.medico_crm’).keypress(function(event) {
var tecla = (window.event) ? event.keyCode : event.which;
if ((tecla > 47 && tecla < 58)) return true;
else {
if (tecla != 8) return false;
else return true;
}
});

Exemplo 2

Por expressão regular.

$(function(){

       $("input[name='nome-do-campo']").bind("keyup blur focus", function(e) {
           e.preventDefault();
           var expre = /[A-Za-z\.\§\£\@\`\Ž\^\~\'\"\!\?\#\$\%\š\¬\_\+\=\.\,\:\;\<\>\|\°\ª\º\]\[\{\}\\ \)\(\*\&\-\/\\]/g;
           // REMOVE OS CARACTERES DA EXPRESSAO ACIMA
           if ($(this).val().match(expre))
               $(this).val($(this).val().replace(expre,''));
       });
});

Exemplo 3

Função:

function verificaNumero(e) {
       if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
             return false;
       }
}

Chamada da Função:
$(document).ready(function() {
	$("#txtCEP").keypress(verificaNumero);
	$("#txtCEP2").keypress(verificaNumero);
	$("#txtCEP3").keypress(verificaNumero);
});

Implementação
01 <html>
02     <head>
03         <title>Teste só numeros</title>
04         <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
05         <script>
06             function verificaNumero(e) {
07                 if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
08                     return false;
09                 }
10             }
11
12             $(document).ready(function() {
13                 $("#txtCEP").keypress(verificaNumero);
14                 $("#txtCEP2").keypress(verificaNumero);
15                 $("#txtCEP3").keypress(verificaNumero);
16             });
17         </script>
18     </head>
19     <body>
20         <input id="txtCEP" type="text"/>
21         <input id="txtCEP2" type="text"/>
22         <input id="txtCEP3" type="text"/>
23     </body>
24 </html>
 

Condeúdo de: http://olhonobit.wordpress.com/2010/10/01/jquery-campo-de-texto-aceitando-so-numeros/