February 23, 2009

`calculable' textboxes using jquery

Here's some code to make your textboxes calculable. Demonstration here.

(function($) {
            $.fn.calculable = function() {
                return this.each(function() {
                    $(this).focus(function(e) {
                        var expr = $(this).attr('calcExpr');
                        if (expr) {
                            $(this).val(expr);
                        }
                    }); // end focus
                    
                    $(this).blur(function(e) {
                        try {
                            var expr = $(this).val();
                            var calculated = eval('with(Math){'+expr+'}');

                            $(this).attr('calcExpr', expr);
                            $(this).val(calculated);
                        }
                        catch (e) {
                            $(this).attr('calcExpr', '');
                        }
                    }); // end blur
                }); // end each
            };
        })(jQuery);

Yes, it uses eval. Doesn't evaluate on initial load. Provides no way to post the expression to the backend.

Expect improvements, and submit patches, once this goes into source control.

edit: Now available in a github repository.