paolo@bimodesign.com | +34 608 61 64 10

JS / Ajax / Jquery / Json

        

Jquery, how to check input values during typing them

This Jquery function allows to check, while the user types char into the input html element, if the value/char will be a part of decimal number and it doesn't allow to type it. A message error will show when the function detects an error during the type and hide it in another cases.
The keypress native function allows to set several options, like a minus number of input char or the max decimal places, that get from a hidden input element called max_decimal_places. I'm using a regexp to check the values, so you'll adapt this function to the other input checks (integer, alpha text, etc..) changing only that code line and the option keypress.
In this post I'll show the complete code for decimal case and after only the part of code that you'll change to adapt for the other cases.

var decimaltextinput = new function() {
    
    this.loadDecimalTextInput = function(componentId){
        $("input").each(function( index, element) {
            if($(element).attr('name').match(componentId)){
                $(element).numeric({
                    allowPlus:    false,
                    allowMinus:   false,
                    allowThouSep: false,
                    allowDecSep:  true,
                    maxDecimalPlaces : $('#max_decimal_places').val()
                });
                
                $(element).keypress(function(e) {
                    if (e.which !== 0) {
                        var keyMessage = $(element).attr('name').split("_");
                        var keyMessageFinal = keyMessage.pop();
                        
                        // To hide always the div error while typing
                        $("#message_error").hide();
                        
                        var regex = /^[0-9.]+$/;
                        if(!regex.test(String.fromCharCode(e.which)) ) {
                            $("#message_error").show();

                            $(element).click(function () {
                                $("#message_error").hide();
                            });
                        }
                    }
                });                  
            };
        });
    }; 
}

Alpha case:

var alphatextinput = new function() {
...
   $(element).alpha();
...
   var regex = /[^a-zA-Z]/;
...
}

Numeric case:

var numerictextinput = new function() {
...
    $(element).numeric({
        allowPlus:    false,
        allowMinus:   false,
        allowThouSep: false,
        allowDecSep:  false
    });
...
   if (isNaN(String.fromCharCode(e.which))) {
...
}