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

JS / Ajax / Jquery / Json

        

Jquery, increase or decrease a numeric input value

This Jquery function allows to add or remove one unit to a input html numeric value. It starts from 0 (and it doesn't allow negative values) but it's possible to type a custom value and then to increase/decrease it.
Note that I'm using keypress native function how I explain in this post.
Note: componentId is the name of the application's component.

var numerictextinputmodifyunit = new function() {
    
    this.loadNumericTextInputModifyUnit = function(componentId){ 
        $("input").each(function( index, element) {
            if($(element).attr('name').match(componentId)){
                $(element).numeric({
                    allowPlus:    false,
                    allowMinus:   false,
                    allowThouSep: false,
                    allowDecSep:  false
                });
                
                $(element).keypress(function(e) {
                    if (e.which !== 0) {

                        // To hide always the div error while typing
                        $("#" + componentId + "_error").hide();
                        
                        if (isNaN(String.fromCharCode(e.which))) {
                            $("#" + componentId + "_error").show();
                            
                            $(element).click(function () {
                                $("#" + componentId + "_error").hide();
                            });                         
                        }
                    }
                }); 
                
                $("#" + componentId + "_remove").click(function(){
                    var currentValue = $("#" + componentId).val();
                    var newValue = parseInt(currentValue) - 1;
                    if(newValue < 0){
                        // It will be always 0
                        $("#" + componentId).val(currentValue);
                    } else {
                        $("#" + componentId).val(newValue);
                    }
                });
                
                $("#" + componentId + "_add").click(function(){
                    var currentValue = $("#" + componentId).val();
                    var newValue = parseInt(currentValue) + 1;
                    $("#" + componentId).val(newValue);
                });
            };
        });
    }
}