jQuery: verificare se l'input utente è numerico

jQuery: verificare se l'input utente è numerico

In jQuery esistono due modi per stabilire se l'input inserito dall'utente è numerico o meno: le espressioni regolari e i codici dei tasti premuti. In questo articolo vedremo questa seconda modalità.

Possiamo creare il seguente plugin per intercettare i tasti premuti dall'utente:


(function($) {
    $.fn.numeric = function(options) {
        
        var that = this;
        options = $.extend({
            success: function() {},
            error: function() {}
        }, options);
        
        return that.each(function() {
    $(that).keydown(function(event){
        if( event.keyCode == 46 || event.keyCode == 8 || (event.keyCode < 41 && event.keyCode > 36) || (event.keyCode < 58 && event.keyCode > 47) || (event.keyCode < 106 && event.keyCode > 94) ){
            
            options.success();
        } else {
         
            options.error();                
            
        }
        
    });
                     
                     });
        
        
    };
    
    
})(jQuery);

Esempio d'uso:


$('#num').numeric({
    success: function() {
        alert('Number');
    },
    error: function() {
        
        alert('NaN');
        
    }});

Potete visionare l'esempio finale in questa pagina.

Torna su