Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, 11 September 2013

create own support Ctrl+v, Ctrl+c, Ctrl+X and 'Numeric only' jquery plugin

(function ($) {
    $.fn.forceNumeric = function () {
        return this.each(function () {
            // bind handler of 'paste' event
            $(this).bind(
                {
                    paste: function (e) {
                        var content = e.originalEvent.clipboardData.getData('text/plain');
                        var regExp = /^\d+$/;
                        if (!regExp.test($.trim(content))) {
                            e.preventDefault();
                        }
                    }
                });
            $(this).keydown(function (e) {
                var key = e.which || e.keyCode;

                if (!e.shiftKey && !e.altKey) {
                    if ((key >= 48 && key <= 57 ||
                        // Numeric keypad
                        key >= 96 && key <= 105 ||
                        // comma, period and minus, . on keypad
                        key == 190 || key == 188 || key == 109 || key == 110 ||
                        // Backspace and Tab and Enter
                        key == 8 || key == 9 || key == 13 ||
                        // Home and End
                        key == 35 || key == 36 ||
                        // left and right arrows
                        key == 37 || key == 39 ||
                        // Del and Ins
                        key == 46 || key == 45) && !e.ctrlKey) {
                        return true;
                    }

                    // Allow: Ctrl+C, Ctrl+V, Ctrl+X
                    if ((e.keyCode == 67 || e.keyCode == 86 || e.keyCode == 88) &&
                        (e.ctrlKey === true || e.metaKey === true)) {
                        return true;
                    }
                }

                return e.preventDefault();
            });
        });
    };
}(jQuery));

Monday, 26 August 2013

tips of jqgrid

  • Define own date formatter
  • $.extend($.fn.fmatter , {
        dateFormatter : function(cellvalue, options, rowObject) {
            if (cellvalue) {
                // parseExact just returns 'null' if the date you are trying to
                // format is not in the exact format specified
                var parsedDate = Date.parseExact(cellvalue, "yyyy-MM-ddTHH:mm:ss");
                if(parsedDate == null )
                    parsedDate = new Date(cellvalue);
    
                // if parsed date is null, just used the passed cell value; otherwise,
                // transform the date to desired format
                var formattedDate = parsedDate ? parsedDate.toString("yyyy-MM-dd HH:mm:ss") : cellvalue;
    
                return formattedDate;
            } else {
                return '';
            }
        }
    });
    
  • Add 'link' column to table
  • $.extend($.fn.fmatter , {
        dynamicLink : function (cellValue, options, rowObject) {
            return "<a href='#' onclick=\"viewReport('" + rowObject.custodyRefNumber + "', '" + rowObject.docketNumber + "');return false;\">view report</a>";
        }
    });
    
  • dynamic setting width/height to match parent component
  • function resizeJqgridWidth() {
        if (grid = $('.ui-jqgrid-btable:visible')) {
            grid.each(function(index) {
                gridId = $(this).attr('id');
                gridParentWidth = $('#gbox_' + gridId).parent().width() - 5;
                $('#' + gridId).setGridWidth(gridParentWidth);
            });
        }
    }
    
  • convert string to javascript json object
  • function convertDotNotationStringToNestJsonObject(data) {
        var obj = {}, t, parts, part;
        for (var k in data) {
            t = obj;
            parts = k.split('.');
            var key = parts.pop();
            while (parts.length) {
                part = parts.shift();
                t = t[part] = t[part] || {};
            }
            t[key] = data[k]
        }
        return obj;
    }
    

Wednesday, 7 December 2011

fibonacci number in javascript under cached way

function fibonacci(n) {
    if (!(n in fibonacci)) {
        if (n == 0) {
           fibonacci.counter++;

           fibonacci[n] = 0;
           return 0;
         }

         if (n == 1) {
            fibonacci.counter++;

            fibonacci[0] = 0;
            fibonacci[1] = 1;
            return 1;
          }
        
          fibonacci.counter++;

          fibonacci[n] = fibonacci(n -1) + fibonacci(n-2);
     }
  
     return fibonacci[n];
}
fibonacci.counter = 0; // for debug
var val1 = fibonacci(10);
var val1 = fibonacci(9);
console.log('counter: ' + fibonacci.counter); // >> counter: 10
var val1 = fibonacci(11);
console.log('counter: ' + fibonacci.counter); // >> counter: 11

Monday, 5 December 2011

static variable in javascript

Functions are not primitive values in JavaScript, but a specialized kind of object, which means that functions can have properties. When a function needs a “static” variable whose value persists across invocations, it is often convenient to use a property of the function, instead of cluttering up the namespace by defining a global variable. You could store this information in a global variable, but that is unnecessary, because the information is used only by the function itself. It is better to store the information in a property of the Function object. So there're two solutions to solve this.
1) using global variable
2) function properties
function uniqueSuffix() {
    uniqueSuffix.counter = uniqueSuffix.counter || 0;
    return uniqueSuffix.counter++;
}

uniqueSuffix();
uniqueSuffix();
console.log(uniqueSuffix.counter); // >>2

Tuesday, 29 November 2011

add remove() function to array of javascript

Array.prototype.indexOf = function(e){
    for (var i = 0; i < this.length; i++) {
        if (e==this[i]) {
            return i;
        }
    }

  return -1;
}

Array.prototype.remove = function(elem) {
    var match = -1;
    while ((match = this.indexOf(elem)) > -1) {
        this.splice(match, 1);
    }
};

How to create an unique array using javascript

Array.prototype.indexOf = function(e){
    for (var i = 0; i < this.length; i++) {
        if (e==this[i]) {
            return i;
        }
    }

  return -1;
}

Array.prototype.unique = function () {
    var values = this;
    var uniqueValues = [];
    for (var i = values.length; i--;) {
        var val = values[i];
        if (uniqueValues.indexOf(val) === -1) {
            uniqueValues.unshift(val);
        }
    }
    return uniqueValues;
};

How to validate Date format in Javascript?

Validate the input Date text is very common in web application. My solution is combine Regular Express and Date object. Using regular express to validate the text under the special pattern(yyyy-MM-dd etc.). Using Date object to validate the year,month, day is reasonable.

function dateValidator(text) {
    var pattern = /^([1-9]\d{3})-(0[1-9]|1[0-2])-([0-2][1-9]|3[0-1])$/;
    if (pattern.test($.trim(text))) {
        var datePart = text.split('-');
        var year = parseInt(datePart[0], 10);
        var month = parseInt(datePart[1], 10) - 1;
        var day = parseInt(datePart[2], 10);
        var date = new Date(year, month, day, 0, 0, 0);

        var y = date.getFullYear();
        var m = date.getMonth();
        var d = date.getDate();

        if ( year == y && month== m && day == d) {
           return true;
        }
    }
    return false;
}