Wednesday, December 4, 2013

Finding maximum value out of different columns

DECLARE @a INT, @b INT, @c INT 

SET @a = 10 
SET @b = 7 
SET @c = 12 

--sql server 2008 and above
SELECT MAX(v) AS MaxVal 
FROM   ( VALUES (@a), 
                (@b), 
                (@c) ) AS value(v) 

--sql server 2005
SELECT MAX(v) AS MaxVal 
FROM   (SELECT @a UNION 
        SELECT @b UNION 
        SELECT @c) AS value(v)

Saturday, November 23, 2013

Ternary Operator in javascript


var eVal = (isNaN(eThis.val())) ? 0 : eThis.val();
var eVal = parseFloat($(eThis).val()) || 0;

GridView Accessible Header

/// 
    /// Adds THeadere TBody tag to gridview
    /// http://dotnetinside.com/en/framework/v4.0.30319/System.Web/TableRow
    /// 
    /// the gridview
public void MakeAccessible(GridView grid)
{
        if (grid == null || grid.Rows.Count <= 0) return;
        //This replaces  with  and adds the scope attribute
grid.UseAccessibleHeader = true;
//This will add the and elements
if (grid.HeaderRow != null) grid.HeaderRow.TableSection = TableRowSection.TableHeader;
if (grid.TopPagerRow != null) grid.TopPagerRow.TableSection = TableRowSection.TableHeader;
//This adds the element. Remove if you don't have a footer row
if (grid.BottomPagerRow != null) grid.BottomPagerRow.TableSection = TableRowSection.TableFooter;
}

Jquery ui datepicker appears off screen fix

/*e.g. $('.ui-datepicker').center();*/
jQuery.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}

Restricting keyboard input with jQuery and validate decimal precision,scale

keycodechecker Demo
txt.Attributes.Add("class", "numbersonly");

In blur or textbox leaving, or in button click call the below function
function IsDecimal(Salary) {
     var _Salary = $('#' + Salary);
     if (!_Salary.isValidScale(6, 2)) {
         _Salary.focus();
         alert('Invalid decimal points');
         return false;
     }
     return true;
 }

/*Numeric validation starts*/

//Allows decimal places with only one .(decimal point or full stop)
$(".numbersonly").keydown(function (event) {
    // Prevent shift key since its not needed
    if (event.shiftKey == true) {
        event.preventDefault();
    }

    // Allow Only: keyboard 0-9, numpad 0-9
    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)
        //Allow Only: backspace, tab, left arrow, right arrow
        || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39
        //Allow Only: delete, home, end
        || event.keyCode == 46 || event.keyCode == 36 || event.keyCode == 35
        //Allow Only: .(full stop [keyboar, numpad]) and check if there is more than one .(full stop)
        || ((event.keyCode == 190 || event.keyCode == 110) && $(this).val().indexOf('.') < 0)
    ) {
        // Allow normal operation
    } else {
        // Prevent the rest
        event.preventDefault();
    }
});

//Validate the count of precision and scale of a decimal value
//ctrlID.isValidScale(6,2);
jQuery.fn.isValidScale = function (precision, scale) {
    //return !Number.isNaN(num) && parseFloat(num).toFixed(scale).toString() === this.val();
    /*          debugger;
         var ina = !isNaN(num);
         var len = decimalPlaces(num)
         var isTrue = decimalPlaces(num) <= parseInt(scale)
         var tr = !isNaN(num) && isTrue;*/

    var num = parseFloat(this.val()) || 0;
    var intPart = parseInt(this.val()).toString(); //Convert to string

    //if input control is empty
    if (num.length == 0) return true;
    if (intPart.length > parseInt(precision)) return false;

    return !isNaN(num) && decimalPlaces(num) <= parseInt(scale);
};

function decimalPlaces(n) {
    var a;
    var len = (a = (n.toString().charAt(0) == '-' ? n - 1 : n + 1).toString().replace(/^-?[0-9]+\.?([0-9]+)$/, '$1').length) >= 1 ? a : 0;
    return parseInt(len);
}

$(".intonly").keydown(function (event) {
    // Prevent shift key since its not needed
    if (event.shiftKey == true) {
        event.preventDefault();
    }
    // Allow Only: keyboard 0-9, numpad 0-9, backspace, tab, left arrow, right arrow, delete, home, end
    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 36 || event.keyCode == 35) {
        // Allow normal operation
    } else {
        // Prevent the rest
        event.preventDefault();
    }
});

var isValidCurrency = function (input) {
    var num = parseFloat(input);
    return !Number.isNaN(num) && parseFloat(num).toFixed(2).toString() === input;
};
/*Numeric validation ends*/

How to get the value of checkboxlist in jquery

For the checboxlist create an attribute for each listitem
/*to get the checkbox value in jquery*/
foreach (ListItem li in cbHideColumns.Items)
{
li.Attributes.Add("someValue", li.Value);
}
How to get the value in jquery
$(".cbShowOrHideGvCols input[type=checkbox]").each(function () {
var checkbox = $(this)
if ($(ctrl).is(":checked")) {
var val = checkbox.parent().attr('someValue');
}
});

jquery - Datatables change language dynamically

1. Consider we need both chinese and english
2. Create 2 text files jquery.dataTables.en-US.txt, jquery.dataTables.zh-CN.txt
3. Go to the url http://datatables.net/plug-ins/i18n
Get the language text and paste it in the relative files.
4. In the masterpage we need to have a hidden control.

5. Store the current language in the hidden field.
hdnLang.Value = SessionProxy.Search.Language.ToLower();
6. Get the language in the javascript file
var locale = ($('#ctl00_hdnLang').val() || "en-us");
7. Dynamically change the datatable language file
var langFile = "../Scripts/jquery.dataTables.en-US.txt";
if (locale === "zh-cn") {
langFile = "../Scripts/jquery.dataTables.zh-CN.txt";
}
8. Using it in the script
var oTable = $('.gvDataTable').dataTable({
    "oLanguage": {
        "sUrl": langFile
    },
    "sScrollX": "99%",
    "bStateSave": true, //http://datatables.net/forums/discussion/573/how-to-stay-on-current-page-after-re-draw/p1
    "fnDrawCallback": function (oSettings) {/*Re-Create serial no for the table*/
        /* Need to redo the counters if filtered or sorted */
        if (oSettings.bSorted || oSettings.bFiltered) {
            for (var i = 0, iLen = oSettings.aiDisplay.length; i < iLen; i++) {
                $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[i]].nTr).html(i + 1);
            }
        }
         /*Put checkboxlist after filter to show/hide columns after excel export*/
        $('.cbShowOrHideGvCols').appendTo('div.DTTT_container'); 
    },
    /*"sDom": 'r<"H"lf><"datatable-scroll"t><"F"ip>',*/
    "sDom": '<"H"lTfr><"datatable-scroll"t><"F"ip>',
    "oTableTools": {
        "sSwfPath": "../Scripts/media/swf/copy_csv_xls_pdf.swf",
        /*"sSwfPath": "http://datatables.net/release-datatables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf",*/
        "aButtons": [{ /*http://datatables.net/extras/tabletools/button_options*/
                "sExtends": "xls",
                "sFileName": "xlsFileName.xls",
                "sButtonText": "",
                "sTitle": "Title of the file"
                /*"fnInit": function (node) { formatTableToolsButton(node, 'DTTT_button_xls'); }*/
            }
            /*, {
"sExtends": "pdf",
//"sButtonText": "",
"sFileName": "PdfFileName.pdf",
"sTitle": "Title of the file"
}*/
        ]
    }
});

/*When we edit the gridview, header and row are zigzag.
Call this to overcome it
*/
setTimeout(function () {
    oTable.fnAdjustColumnSizing();
}, 50);

/*after page load call this event, if there is a postback*/
if ($('.gvShowOrHideGvCols tr').length <= 0) $(".cbShowOrHideGvCols").css("display", "none");
$(".cbShowOrHideGvCols input[type=checkbox]").each(function () {
    ToggleGridViewCol('.gvShowOrHideGvCols', this, '');
});

/*when the checkbox checked changed*/
$(".cbShowOrHideGvCols input[type=checkbox]").change(function () {
    ToggleGridViewCol('.gvShowOrHideGvCols', this, '');
});

/*Remarks: if we want to show or hide gridview columns
  grid: GridView.ClientID
  ctrl: CheckBoxList control(if we are using foreach)
  colIndex: gridview column index we need to show/hide
  someValue: this the attribute added to the checkbox, which holds the checkbox value
  */
function ToggleGridViewCol(grid, ctrl, colIndex) {
    var col = (colIndex === '') ?
        $(ctrl).parent().attr('someValue') : colIndex;

    if (col != '') {
        var show = $(ctrl).is(":checked");
        if ($(grid + " tr").length <= 0) return true; //check gridview loaded/empty
        var oTable = $(grid).dataTable();
        var bVis = oTable.fnSettings().aoColumns[col].bVisible;

        if (show && !bVis)
            oTable.fnSetColumnVis(col, true);
        else if (!show && bVis)
            oTable.fnSetColumnVis(col, false);
    }
}

Wednesday, November 6, 2013

jQuery DataTables mouseover cursor issue

For the disabled text of the jquery datatable it show hand or pointer.
To show default cursor use the below css at the end of DataTable.css

.paginate_disabled_previous, .paginate_disabled_next,
.paginate_disabled_previous:hover, .paginate_disabled_next:hover
{
cursor: default;
text-decoration:none;
}

Check the below links for the cursor and text decoration demo from w3schools

Cursor
text-decoration

Friday, August 2, 2013

show popup window minimized

var win;

    function openWindow() {
        if (win == null || win.closed == true) {
            win = window.open('Help.htm', 'Help', 'top=150,left=200,width=450,height=250,resizable=yes,scrollbars=yes');
            win.focus();
            return false;
        } else {
            win.target = "Help.htm";
            win.focus();
            return false;
        }
    }
How to call

OnClientClick="javascript:return openWindow();"