Monday, 7 August 2017

Add Filter in HTML table header using jquery


1. If you have data in array list then copy below function and modify as per your requirement.




function ShowFinalTable()
{

    var finalQuestionArrayList = new Array();
    var questionNoArrayList = new Array();
    var finalFormSetTableArrayList = new Array();
    var itemInformationArrayList = new Array();
    var difficlityArrayList = new Array();
    var complexityArrayList = new Array();
    var conareatextArrayList = new Array();
    var subcontentareatextArrayList = new Array();
    for (var i = 0; i < preTest_formSetsQuations.length; i++)
    {
        var formSet = {};
            formSet.FormSet = "Pre-Test";
            formSet.Question = preTest_formSetsQuations[i];
            finalQuestionArrayList.push(formSet);    
    }
    for (var i = 0; i < anchor_formSetsQuations.length; i++)
    {
        var formSet = {};
        formSet.FormSet = "Anchor";
        formSet.Question = anchor_formSetsQuations[i];
        finalQuestionArrayList.push(formSet);  
    }
    for (var i = 0; i < unique_formSetsQuations.length; i++)
    {
        var formSet = {};
        formSet.FormSet = unique_formSetsQuations[i].FormSet;
        formSet.Question = unique_formSetsQuations[i].Question;
        finalQuestionArrayList.push(formSet);
    }  
    var items = completeUniqueQuestionBankArray;
    var txtquestionNo=   "<br /><select type='text' id='txtquestionNo' class='rowSearchHeader' style='display:none'  onchange='searchRows(tableFinalResult)'></select>";
    var txtFormSet = "<br /><select type='text' id='ddlFinalFormSet' class='rowSearchHeader' onchange='searchRows(tableFinalResult)'></select>";
    var txtcontentArea = "<br /><select type='text' id='txtcontentArea' class='rowSearchHeader'   onchange='searchRows(tableFinalResult)'></select>";
    var txtsubContentArea = "<br /><select type='text' id='txtsubContentArea' class='rowSearchHeader'  onchange='searchRows(tableFinalResult)'></select>";
    var txtitemInformation = "<br /><select type='text' id='txtitemInformation' class='rowSearchHeader'   onchange='searchRows(tableFinalResult)'></select>";
    var txtdifficulty = "<br /><select type='text' id='txtdifficulty' class='rowSearchHeader'    onchange='searchRows(tableFinalResult)'></select>";
    var txtcomplexity = "<br /><select type='text' id='txtcomplexity' class='rowSearchHeader'   onchange='searchRows(tableFinalResult)'></select>";



    var tbody = "<div id='mainTablearea1'><table cellpadding='0' id='tableFinalResult' cellspacing='0' border='0' id='table' class='tinytable table table-bordered'></div><thead><tr style='background-color: #16629e;color: white;font-size: 11px;'><th class='nosort'>" + $('#colRequeNo').val() + txtquestionNo + "</th><th>FormSet" + txtFormSet + "</th><th>Content Area" + txtcontentArea + "</th><th>Sub Content Area" + txtsubContentArea + "</th><th>Item Information" + txtitemInformation + "</th><th>Difficulty" + txtdifficulty + "</th><th>Complexity" + txtcomplexity + "</th></tr></thead><tbody id='searchDatafinal' style='font-size: 11px;background-color: #fff;'>";
    var tr = "<tr class='rowSearch'>";
    var questionNo = "";
    for (var i = 0; i < items.length; i++)
    {
        var indexValue = finalQuestionArrayList.findIndex(x => x.Question == items[i].ID);
        var valueOfFormSet = "";
        if (indexValue != -1)
        {
            valueOfFormSet = finalQuestionArrayList[indexValue].FormSet;
            questionNo = items[i].ID;
         
            var itemInformation = items[i].ItemInformation;
            if (itemInformation == null) {
                itemInformation = "";
            }
            var difficlity = items[i].DifficulityText;
            if (difficlity == null) {
                difficlity = "";
            }
            var complexity = items[i].ComplexityText;
            if (complexity == null) {
                complexity = "";
            }
            var conareatext = items[i].ContentAreaText;
            if (conareatext == null) {
                conareatext = "";
            }
            var subcontentareatext = items[i].SubContentAreaText;
            if (subcontentareatext == null) {
                subcontentareatext = "";
            }
            tr = tr + "<td><a>" + questionNo + " </a></td><td>" + valueOfFormSet + "</td><td>" + conareatext + "</td><td>" + subcontentareatext + "</td><td>" + itemInformation + "</td><td>" + difficlity + "</td><td>" + complexity + "</td></tr>";
       
            if (questionNoArrayList.toString().indexOf(questionNo) == -1)
            {
                questionNoArrayList.push(questionNo);
            }
         
            if (finalFormSetTableArrayList.toString().indexOf(valueOfFormSet) == -1)
            {
                finalFormSetTableArrayList.push(valueOfFormSet);
            }
            if (itemInformationArrayList.toString().indexOf(itemInformation) == -1) {
                itemInformationArrayList.push(itemInformation);
            }
            if (difficlityArrayList.toString().indexOf(difficlity) == -1) {
                difficlityArrayList.push(difficlity);
            }
            if (complexityArrayList.toString().indexOf(complexity) == -1) {
                complexityArrayList.push(complexity);
            }
            if (conareatextArrayList.toString().indexOf(conareatext) == -1) {
                conareatextArrayList.push(conareatext);
            }
            if (subcontentareatextArrayList.toString().indexOf(subcontentareatext) == -1) {
                subcontentareatextArrayList.push(subcontentareatext);
            }
        }
    }
    var completebody = tbody  +tr + "</tr></tbody></table>";
    var dvTable = $("#mainDivFinalTable");
    dvTable.html("");
    //Append HTML in Main Div Area
    dvTable.append(completebody);

    $('#txtquestionNo').append('<option value="0">Select...</option>');
    for (var index = 0; index < questionNoArrayList.length; index++)
    {
        $('#txtquestionNo').append('<option value="' + questionNoArrayList[index] + '">' +  questionNoArrayList[index] + '</option>');
    }
    $('#ddlFinalFormSet').append('<option value="0">Select...</option>');
    for (var index = 0; index < finalFormSetTableArrayList.length; index++) {
        $('#ddlFinalFormSet').append('<option value="' + finalFormSetTableArrayList[index] + '">' + finalFormSetTableArrayList[index] + '</option>');
    }
    $('#txtcontentArea').append('<option value="0">Select...</option>');
    for (var index = 0; index < conareatextArrayList.length; index++) {
        $('#txtcontentArea').append('<option value="' + conareatextArrayList[index] + '">' + conareatextArrayList[index] + '</option>');
    }
    $('#txtsubContentArea').append('<option value="0">Select...</option>');
    for (var index = 0; index < subcontentareatextArrayList.length; index++) {
        $('#txtsubContentArea').append('<option value="' + subcontentareatextArrayList[index] + '">' +  subcontentareatextArrayList[index] + '</option>');
    }
    $('#txtitemInformation').append('<option value="0">Select...</option>');
    for (var index = 0; index < itemInformationArrayList.length; index++) {
        $('#txtitemInformation').append('<option value="' + itemInformationArrayList[index] + '">' +  itemInformationArrayList[index] + '</option>');
    }
    $('#txtdifficulty').append('<option value="0">Select...</option>');
    for (var index = 0; index < difficlityArrayList.length; index++) {
        $('#txtdifficulty').append('<option value="' + difficlityArrayList[index] + '">' +  difficlityArrayList[index] + '</option>');
    }
    $('#txtcomplexity').append('<option value="0">Select...</option>');
    for (var index = 0; index < complexityArrayList.length; index++) {
        $('#txtcomplexity').append('<option value="' + complexityArrayList[index] + '">' +  complexityArrayList[index] + '</option>');
    }
 
}


2. Copy below method and change the control header according to requirement .
in below script added the dropdown in header to filter the data but if you want to change to text box then replace select with input 





function searchRows(tblId) {
    var tbl = document.getElementById('tableFinalResult');
    var headRow = tblId.rows[0];
    var arrayOfHTxt = new Array();
    var arrayOfHtxtCellIndex = new Array();

    for (var v = 0; v < headRow.cells.length; v++) {
        if (headRow.cells[v].getElementsByTagName('select')[0])
        {
            var Htxtbox = headRow.cells[v].getElementsByTagName('select')[0];
            if (Htxtbox.value != 0) {
                if (Htxtbox.value.replace(/^\s+|\s+$/g, '') != '') {
                    arrayOfHTxt.push(Htxtbox.value.replace(/^\s+|\s+$/g, ''));
                    arrayOfHtxtCellIndex.push(v);
                }
            }
        }
    }

    for (var i = 1; i < tbl.rows.length; i++) {
        tbl.rows[i].style.display = 'table-row';
        for (var v = 0; v < arrayOfHTxt.length; v++) {
            var CurCell = tbl.rows[i].cells[arrayOfHtxtCellIndex[v]];
            var CurCont = CurCell.getElementsByTagName('span')[0];
            var reg = new RegExp(arrayOfHTxt[v] + ".*", "i");
            if (!CurCont) {
                CurCont = tbl.rows[i].cells[arrayOfHtxtCellIndex[v]];
            }
            if (CurCont.innerHTML.match(reg) == null) {
                tbl.rows[i].style.display = 'none';
            }
        }
    }

}

3. Below will be result 










Wednesday, 2 August 2017

Create Dynamic HTML Table with edit functionality using jquery

1.


 <table class="table table-bordered matrixTable" id="uniqueTableMatrix">
                                                                            <thead class="matrixTableHeader">
                                                                                <tr>
                                                                                    <td rowspan='2'>Content Area</td>
                                                                                    <td rowspan='2'>No of Item</td>
                                                                                    <td rowspan='2'>Sub Area</td>
                                                                                    <td rowspan='2'>No of Item</td>
                                                                                    <td colspan='3'>Difficulty Level 1</td>
                                                                                    <td colspan='3'>Difficulty Level 2</td>
                                                                                    <td colspan='3'>Difficulty Level 3</td>
                                                                                    <td rowspan='2'>Action</td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td>C 1</td>
                                                                                    <td>C 2</td>
                                                                                    <td>C 3</td>
                                                                                    <td>C 1</td>
                                                                                    <td>C 2</td>
                                                                                    <td>C 3</td>
                                                                                    <td>C 1</td>
                                                                                    <td>C 2</td>
                                                                                    <td>C 3</td>
                                                                                </tr>
                                                                            </thead>
                                                                            <tbody id="tblBodyMatrix"></tbody>

                                                                            <tfoot class="matrixTableFooter" id="questionsMatrixTableFooter">
                                                                                <tr class="totalColumn">
                                                                                    <td class="totalCol">Total:</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol"></td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol"></td>
                                                                                </tr>
                                                                            </tfoot>
                                                                        </table>







2.


$(document).ready(function () {
  uniqeQuestions.AddMore();
    uniqeQuestions.CellChangeTotal();
    uniqeQuestions.CellMaxLengthValodation();
});



3.

var uniqeQuestions ={
AddMore:function () {
    uniqeQuestions.RemoveMatrixRow();
        $('#btnAddmoreMatrix').click(function () {
            if ($("#ddlContentArea").prop('selectedIndex') != 0) {
                var contentareaID = $('#ddlContentArea').val();
                var rowIndex = uniqeQuestions.FindRowContent(contentareaID);
                var contentItem = $('#txtAreaItem').val();
                if (uniqeQuestions.ContentAreaitemValueValidation(rowIndex, contentItem)) {
                    contentItem = $('#txtAreaItem').val();
                    if (uniqeQuestions.ValidateMatrixTotalRequiedItems()) {
                        if (uniqeQuestions.ValidateDuplicateContentAreaSubContentArea()) {
                            var contentarea = $("#ddlContentArea option:selected").text();


                            var subArea = $("#ddlSubArea option:selected").text();
                            var subAreaID = $('#ddlSubArea').val();
                            if (rowIndex.length >= 1 || rowIndex.length == null)//Content area exist in matrix
                            {

                                var trRow = "<tr class='single'><td class='rowDataSd'><label class='contentAreaID' style='display:none;'>" + contentareaID + "</label><label class='contentAreaText' style='display:none;'>" + contentarea + "</label></td><td class='rowDataSd'>" + contentItem + "</td><td class='rowDataSd'><label class='subAreaID' style='display:none;'>" + subAreaID + "</label>" + subArea + "</td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c3'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c3'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c3'  /></td><td><a href='#' class='remove_MatrixRow'>Remove</a></td></tr>";
                                $('#uniqueTableMatrix > tbody > tr').eq(rowIndex).after(trRow);
                            }
                            else //else if content area does not exist in matrix
                            {
                                var trRow = "<tr class='single'><td class='rowDataSd'><label class='contentAreaID' style='display:none;'>" + contentareaID + "</label><label class='contentAreaText'>" + contentarea + "</label></td><td class='rowDataSd'>" + contentItem + "</td><td class='rowDataSd'><label class='subAreaID' style='display:none;'>" + subAreaID + "</label>" + subArea + "</td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c3'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c3'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c3'  /></td><td><a href='#' class='remove_MatrixRow'>Remove</a></td></tr>";
                                $('#tblBodyMatrix').append(trRow);
                            }
                            uniqeQuestions.RemoveMatrixRow();
                            uniqeQuestions.CellChangeTotal();
                            uniqeQuestions.CellMaxLengthValodation();
                            uniqeQuestions.TotalRowFooter();
                         
                        }
                    }
                }
            }
            else {
                alert('Please select content area !');
            }

        });
    },
ContentAreaitemValueValidation: function (rowIndex, contentItem)
{
var flag = true;
if (rowIndex.length >= 1 || rowIndex.length == null)
{
    $('#txtAreaItem').val('');
}
else
{
    if(contentItem==null || contentItem=="")
    {
        alert('Please enter content area item value !');
        flag = false;
    }
}
return flag;
},
RemoveMatrixRow:function()
{

    $(".remove_MatrixRow").unbind().click(function ()
    {
        if (!uniqeQuestions.ShiftRowDataNextRow($(this).closest(".single")))
        {
            $(this).closest(".single").remove();
        }
        else {
            $(this).closest(".single").remove();
        }
        uniqeQuestions.ResetAllTableData();
        uniqeQuestions.TotalRowFooter();
    });

},
ShiftRowDataNextRow:function (singleRow)
{
    var cellContentAreaCell = singleRow.find('.contentAreaText');
    var cellContentAreaId = singleRow.find('.contentAreaID').text();
    var currentCellValue = singleRow.find('td')[1].innerText;
    var flag = false;
    if (!$(cellContentAreaCell).is(':hidden'))
    {    
        var nextRow = $(singleRow).next('tr.single');
        var nextContentAreaId = nextRow.find('.contentAreaID').text();
        if (nextContentAreaId == cellContentAreaId)
        {
            $(singleRow).next('tr.single').find('.contentAreaText').show();//show the content area
            var s = $(singleRow).next('tr.single').find('td'); //Shuffle  the value of Content AreaItem
            s[1].innerText = currentCellValue;
        }
        flag = true;
    }
    return flag;
},
FindRowContent:function (conterntAreaId)
{
    var rowIndex = "";
    $("#tblBodyMatrix tr").each(function ()
    {
        if (conterntAreaId ==$(this).find('.contentAreaID').html())
        {
            rowIndex = $(this).index();
        }
    });
    return rowIndex;
},
CellMaxLengthValodation:function ()
{
    $(document).on('input', '.cellValidation', function ()
    {
        var allowedDigits = 2;
        var length = $(this).val().length;
        var max = parseInt($(this).attr("max"));
        if ($(this).val() == "") {
            $(this).val("");
        }
        if ($(this).val().indexOf('.') != -1) {
            allowedDigits = 3;
        }
        if (length > allowedDigits) {
            $(this).val($(this).val().substring(1));
        }
        if ($(this).val() > max && max > 0)
        {
            $(this).val($(this).val().substring(1));
        }


    });
},
CellChangeTotal:function ()
{
    $(".matrixQuestionNo").unbind().change(function ()
    {

        var $row = jQuery(this).closest('tr');
        var $columns = $row.find('td');
        ////To Check the limit of SubArea Item and total of difficulty &complexity ///////
        var subAreaItemLimit = 0;
        var sumSubAreaItem = 0;
        var contentAreaID = "";
        var subContentAreaId = "";
        jQuery.each($columns, function (i, item)
        {
            if (i == 0)
            {
                contentAreaID = $(item).find('.contentAreaID').text();
            }
            if (i == 2)
            {
                subContentAreaId = $(item).find('.subAreaID').text();
            }
            if ($(item).find('input').length != 0)
            {
                if (i == 3)
                {
                    var itemValue = $(item).find('input').val();
                    if (itemValue == "" || itemValue == null)
                    {
                        itemValue = 0;
                    }
                    subAreaItemLimit = parseInt(itemValue);
                     
                }
                else
                {
                    var itemValue = $(item).find('input').val();
                    if (itemValue == "" || itemValue == null)
                    {
                        itemValue = 0;
                    }
                    sumSubAreaItem = parseInt(sumSubAreaItem) + parseInt(itemValue);
                }
            }
        });
        if (sumSubAreaItem > subAreaItemLimit)
        {
            if ($(this).parent('td').index() == 3)
            {
                var tableRow = $(this).parent('td').parent('tr');
                uniqeQuestions.OnSubAreaLimitChange(tableRow);
                uniqeQuestions.ResetAllTableData();
            }
            else
            {
                alert('Please check sub area item limit :' + subAreaItemLimit);
                $(this).val('');
                $(this).focus();
            }
        }
        if (sumSubAreaItem <= subAreaItemLimit)
        {
            uniqeQuestions.ValidateSubAreaItemsTotal();
            uniqeQuestions.ResetAllTableData();
        }
        uniqeQuestions.TotalRowFooter();
    });
},
FinalValidation:function ()
{
    var contentItemsTotal = 0;
    var contentSubAreaItemsTotal = 0;
    var matrixItemsTotal = 0;
    var flag = true;
    $("#uniqueTableMatrix td.totalCol").each(function (i)
    {
        if (i ==1)
        {
            if ($(this).html() != "" )
            {
                contentItemsTotal = parseInt($(this).html());
            }
        }
        if (i == 3)
        {
            if ($(this).html() != "") {
                contentSubAreaItemsTotal = parseInt($(this).html());
            }
        }
        if (i == 13)
        {
            if ($(this).html() != "") {
                matrixItemsTotal = parseInt($(this).html());
            }
        }

    });
    if(contentSubAreaItemsTotal<contentItemsTotal)
    {
        alert('Sub area item total is less than the content area item total !');
        flag = false;
    }
    else if(matrixItemsTotal<contentSubAreaItemsTotal)
    {
        alert('Your selected items is less than required items !');
        flag = false;
    }
    else if (matrixItemsTotal == 0)
    {
        alert('There is no item added in matrix table !');
        flag = false;
    }
    return flag;
},
OnSubAreaLimitChange:function (tableRow)
{
    $(tableRow).each(function ()
    {
        $('td', this).each(function ()
        {
            if ($(this).index() != 3)
            {
                $(this).find('input').val('');
            }
        });
    });
},
ResetAllTableData:function ()
{
    unique_formSetsQuations = [];
    var contentAreaId = "";
    var subContentAreaId = "";
    $("#tblBodyMatrix tr td").each(function ()
    {
        if ($(this).index() == 0)
        {
            contentAreaId = $(this).find('.contentAreaID').text();
        }
        if ($(this).index() == 2)
        {
            subContentAreaId = $(this).find('.subAreaID').text();
        }
        if ($(this).index() > 3 && $(this).index() < 13)
        {
            var difficulityComplexity = $(this).find('input').attr('class').split(' ')[3];
            var cellValue = $(this).find('input').val();
            var difficulityLevelComplexityLevel = uniqeQuestions.GetDifficulityComplexity(difficulityComplexity);
            var difficulity = difficulityLevelComplexityLevel.split('#')[0];
            var complexity = difficulityLevelComplexityLevel.split('#')[1];
            if (cellValue == null || cellValue == "")
            {
                cellValue = "";
            }
            if (cellValue != "")
            {
                var result = uniqeQuestions.MatrixRule(contentAreaId, subContentAreaId, difficulity, complexity, cellValue);
                if(result==1)
                {
                    $(this).find('input').val('');
                }
            }
        }    
    });
},
ValidateSubAreaItemsTotal:function ()
{

    var contentAreaId = "";
    var subContentAreaId = "";
    var itemsTotal = 0;
    var cellValueItemSum = 0;
    var valueChanged = false;
    var eventStop = true;
    $("#tblBodyMatrix tr").each(function ()
    {
        $('td', this).each(function ()
        {        
            if ($(this).index() == 0)
            {
                if (contentAreaId != $(this).find('.contentAreaID').text())
                {
                    itemsTotal = 0;
                    cellValueItemSum = 0;
                }  
                contentAreaId = $(this).find('.contentAreaID').text();
            }
            if ($(this).index() == 1)
            {

                if ($(this).html() != "")
                {
                    itemsTotal = parseInt($(this).html());            
                }
            }
            if ($(this).index() ==3)
            {

                var cellValue = $(this).find('input').val();
                if (cellValue == null || cellValue == "")
                {
                    cellValue = "";
                }
                if (cellValue != "")
                {
                    cellValueItemSum = cellValueItemSum + parseInt(cellValue);
                }
            }
        });
        if (itemsTotal < cellValueItemSum)
        {
            if (eventStop == true)
            {
                alert("Content sub area total can't be more than content area total ! ")
                uniqeQuestions.ClearCurrentRowCellsValue(this);
                eventStop = false;
            }
        }
     
    });
},
ClearCurrentRowCellsValue:function (tableRow)
{
    $(tableRow).each(function ()
    {
        $('td', this).each(function ()
        {
            $(this).find('input').val('');
        });
    });
},
ValidateDuplicateContentAreaSubContentArea:function ()
{
    var validationflag = true;
    var contentAreaId = "";
    var subContentAreaId = "";
    var ddlContentArea = $('#ddlContentArea').val();
    var ddlSubArea = $('#ddlSubArea').val();
    $("#tblBodyMatrix tr td").each(function ()
    {
        if ($(this).index() == 0)
        {      
            contentAreaId = $(this).find('.contentAreaID').text();
            subContentAreaId = "";
        }
        if ($(this).index() == 2)
        {
         
            subContentAreaId = $(this).find('.subAreaID').text();
        }
        if (contentAreaId == ddlContentArea && subContentAreaId == ddlSubArea)
        {
            if (validationflag)
            {
                alert("This content area and sub content area is already added in matrix  !");
                validationflag = false;
                contentAreaId = "";
            }
        }
    });
    return validationflag;
},
ValidateMatrixTotalRequiedItems:function ()
{
    var validationflag = true;
    var totalRequiredItems = parseInt($('#txtUnique').val());
    var txtAreaItem = $('#txtAreaItem').val();
    var getFooterTableTotal = 0;
    $("#questionsMatrixTableFooter tr td").each(function ()
    {
        if ($(this).index() == 1)
        {
            if ($(this).html() != "") {
                getFooterTableTotal = parseInt($(this).html());
            }
        }
     
    });
    var total = parseInt(getFooterTableTotal) + parseInt(txtAreaItem);
    if(total > totalRequiredItems)
    {
        alert("Please check the required items limit and matrix items ,You are trying to add more items than the required items !");
        validationflag = false;
    }
    return validationflag;
},
TotalRowFooter:function ()
{
    var totals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    var $dataRows = $("#tblBodyMatrix tr:not('.totalColumn, .titlerow')");
    $dataRows.each(function () {

        $(this).find('.rowDataSd').each(function (i) {

            var s = $(this).find('input').val();
            if ($(this).find('input').length == 0)
            {
                s = $(this).html();
            }
            if ($.isNumeric(parseInt(s))) {
           
                totals[i] += parseInt(s);
            }
        });
    });
    var itemsSum = 0;
    $("#uniqueTableMatrix td.totalCol").each(function (i)
    {
        if (i != 0 && i != 1 && i != 2 && i != 3 && i !=13)
        {
            itemsSum = itemsSum + parseInt(totals[i]);
        }
        if (i == 0)
        {
            $(this).html("Total :");
        }
        else
        {
            if (i == 2 || i ==13)
            {
                if (i == 13)
                {

                    $(this).html(itemsSum);
                }
                else
                {
                    $(this).html('');
                }
            }
            else
            {
             
                $(this).html(totals[i]);
            }
        }
     
    });

}}

Below will be result




Monday, 31 July 2017

Color picker in jquery and HTML









Below is reference







<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"></link>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script>
  $(document).ready(function(){
  $('#btnSubmit').click(function(){
 alert( $('#colorId').val());
});
 

  });

  </script>
  <input type="button" id='btnSubmit' class="btn btn-default" value='Get Color Code' />
     <input type="color" class="form-control" id="colorId">

Thursday, 29 June 2017

How to make a list of Object in JavaScript



How to make a list of Object  in JavaScript


<script>
 var cityObject= GetCityObjectArray();
for(var i=0;i<cityObject.length;i++)
{    
       alert(cityObject[i].Name);
}
 function GetCityObjectArray()
 {
        var cities = new Array();    
        for(var i=0;i<=10;i++)
        {  var city = {};
           city.Name = i;
           city.Population = i;
           cities.push(city);
        }
       console.log(cities);
       return cities;
  }
</script>



Parse date from string to any date format

Parsing date from string  to cultural format



string timeFrameFromDate=date;

 lstItem["FromDate"] = DateTime.ParseExact(timeFrameFromDate, "dd/M/yyyy", CultureInfo.InvariantCulture);

Date Format Output will be  like this      31/12/2017



And Use below code to convert date in different format

function getFormattedDate(formatedDate) {
    var year = formatedDate.getFullYear();
    var month = (1 + formatedDate.getMonth()).toString();
    month = month.length > 1 ? month : '0' + month;
    var day = formatedDate.getDate().toString();
    day = day.length > 1 ? day : '0' + day;
    return day + '/' + month + '/' + year;

}




Friday, 16 June 2017

Get AD User Using WCF Service and Ajax Call

1. Create WCF Service Application Project

2. Copy below code and paste in IService1 interface class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace ActiveDirectoryDetails
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetADUsers/?domain={domain}&userid={userid}&password={password}")]
        List<Users> GetADUsers(string domain, string userid, string password);
    }

    [DataContract]
    public class Users
    {
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string MiddleName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
        public string FullName { get; set; }
        [DataMember]
        public string LogonName { get; set; }
        [DataMember]
        public string Email { get; set; }
        [DataMember]
        public string Department { get; set; }
        [DataMember]
        public string Designation { get; set; }
        [DataMember]
        public string Company { get; set; }
        [DataMember]
        public string GroupName { get; set; }
        [DataMember]
        public string Manager { get; set; }
        [DataMember]
        public string Reporting { get; set; }
        [DataMember]
        public string MobileNumber { get; set; }
        [DataMember]
        public string Status { get; set; }
        [DataMember]
        public string PostalAddresses { get; set; }
        [DataMember]
        public string Country { get; set; }
        [DataMember]
        public string StateProvince { get; set; }
        [DataMember]
        public string City { get; set; }
        [DataMember]
        public string ZIPPostalCode { get; set; }
        [DataMember]
        public string HomeAddress { get; set; }
        [DataMember]
        public string StreetAddress { get; set; }
        [DataMember]
        public string CountryAbbreviation { get; set; }
        [DataMember]
        public string HomePhone { get; set; }
        [DataMember]
        public string OfficeLocation { get; set; }
        [DataMember]
        public string ExtensionName { get; set; }
        [DataMember]
        public string OtherEMailAddress { get; set; }
        [DataMember]
        public string OtherMobileNumber { get; set; }

    }


}


3. Copy below code and paste in Service1 class



using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.DirectoryServices;
//using Microsoft.Web.Hosting.Administration;
namespace ActiveDirectoryDetails
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {

        public List<Users> GetADUsers(string domain, string userid, string password)
        {
            List<Users> lstADUsers = new List<Users>();
            try
            {
                string domainName = domain;
                DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + domainName, null, null);
                DirectorySearcher search = new DirectorySearcher(searchRoot);
                search.Filter = "(&(objectClass=user)(objectCategory=person))";
                searchRoot.Username = userid;
                searchRoot.Password = password;
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");
                search.PropertiesToLoad.Add("department");
                search.PropertiesToLoad.Add("manager");
                search.PropertiesToLoad.Add("userAccountControl");
                search.PropertiesToLoad.Add("company");
                search.PropertiesToLoad.Add("givenName");
                search.PropertiesToLoad.Add("sn");
                search.PropertiesToLoad.Add("c");
                search.PropertiesToLoad.Add("co");
                search.PropertiesToLoad.Add("homePostalAddress");
                search.PropertiesToLoad.Add("l");
                search.PropertiesToLoad.Add("postalCode");
                search.PropertiesToLoad.Add("st");
                search.PropertiesToLoad.Add("streetAddress");
                search.PropertiesToLoad.Add("postalAddress");
                search.PropertiesToLoad.Add("homePhone");
                search.PropertiesToLoad.Add("mobile");
                search.PropertiesToLoad.Add("middleName");
                search.PropertiesToLoad.Add("Title");
                search.PropertiesToLoad.Add("directReports");
                search.PropertiesToLoad.Add("physicalDeliveryOfficeName");
                search.PropertiesToLoad.Add("extensionName");
                search.PropertiesToLoad.Add("otherMailbox");
                search.PropertiesToLoad.Add("otherMobile");
                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        Users objSurveyUsers = new Users();
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname"))
                        {
                            objSurveyUsers.LogonName = (String)result.Properties["samaccountname"][0];
                        }
                        if (result.Properties.Contains("mail"))
                        {
                            objSurveyUsers.Email = (String)result.Properties["mail"][0];
                        }
                        if (result.Properties.Contains("displayname"))
                        {
                            objSurveyUsers.FullName = (String)result.Properties["displayname"][0];
                        }
                        if (result.Properties.Contains("department"))
                        {
                            objSurveyUsers.Department = (String)result.Properties["department"][0];
                        }
                        if (result.Properties.Contains("manager"))
                        {
                            objSurveyUsers.Manager = (String)result.Properties["manager"][0];
                        }

                        if (result.Properties.Contains("userAccountControl"))
                        {

                            objSurveyUsers.Status = IsActive(Convert.ToInt32((int)result.Properties["userAccountControl"][0]));
                        }
                        if (result.Properties.Contains("givenName"))
                        {

                            objSurveyUsers.FirstName = (String)result.Properties["givenName"][0];
                        }
                        if (result.Properties.Contains("usergroup"))
                        {

                            objSurveyUsers.GroupName = (String)result.Properties["usergroup"][0];
                        }
                        if (result.Properties.Contains("sn"))
                        {

                            objSurveyUsers.LastName = (String)result.Properties["sn"][0];
                        }
                        if (result.Properties.Contains("c"))
                        {

                            objSurveyUsers.CountryAbbreviation = (String)result.Properties["c"][0];
                        }
                        if (result.Properties.Contains("co"))
                        {

                            objSurveyUsers.Country = (String)result.Properties["co"][0];
                        }
                        if (result.Properties.Contains("homePostalAddress"))
                        {

                            objSurveyUsers.HomeAddress = (String)result.Properties["homePostalAddress"][0];
                        }
                        if (result.Properties.Contains("l"))
                        {

                            objSurveyUsers.City = (String)result.Properties["l"][0];
                        }
                        if (result.Properties.Contains("postalCode"))
                        {

                            objSurveyUsers.ZIPPostalCode = (String)result.Properties["postalCode"][0];
                        }
                        if (result.Properties.Contains("st"))
                        {

                            objSurveyUsers.StateProvince = (String)result.Properties["st"][0];
                        }
                        if (result.Properties.Contains("streetAddress"))
                        {

                            objSurveyUsers.StreetAddress = (String)result.Properties["streetAddress"][0];
                        }
                        if (result.Properties.Contains("postalAddress"))
                        {

                            objSurveyUsers.PostalAddresses = (String)result.Properties["postalAddress"][0];
                        }
                        if (result.Properties.Contains("homePhone"))
                        {

                            objSurveyUsers.HomePhone = (String)result.Properties["homePhone"][0];
                        }
                        if (result.Properties.Contains("mobile"))
                        {

                            objSurveyUsers.MobileNumber = (String)result.Properties["mobile"][0];
                        }
                        if (result.Properties.Contains("middleName"))
                        {

                            objSurveyUsers.MiddleName = (String)result.Properties["middleName"][0];
                        }
                        if (result.Properties.Contains("Title"))
                        {

                            objSurveyUsers.Designation = (String)result.Properties["Title"][0];
                        }
                        if (result.Properties.Contains("directReports"))
                        {

                            objSurveyUsers.Reporting = (String)result.Properties["directReports"][0];
                        }
                        if (result.Properties.Contains("physicalDeliveryOfficeName"))
                        {

                            objSurveyUsers.OfficeLocation = (String)result.Properties["physicalDeliveryOfficeName"][0];
                        }
                        if (result.Properties.Contains("extensionName"))
                        {

                            objSurveyUsers.ExtensionName = (String)result.Properties["extensionName"][0];
                        }
                        if (result.Properties.Contains("otherMailbox"))
                        {

                            objSurveyUsers.OtherEMailAddress = (String)result.Properties["otherMailbox"][0];
                        }
                        if (result.Properties.Contains("otherMobile"))
                        {

                            objSurveyUsers.OtherMobileNumber = (String)result.Properties["otherMobile"][0];
                        }
                        if (result.Properties.Contains("company"))
                        {

                            objSurveyUsers.Company = (String)result.Properties["company"][0];
                        }

                        lstADUsers.Add(objSurveyUsers);

                    }
                }
            }
            catch (Exception ex)
            {

            }
            return lstADUsers;
        }
        public string IsActive(int value)
        {
            string status = string.Empty;
            if (value == 66050)
            {
                status = "DeActive";
            }
            else
            {
                status = "Active";
            }
            return status;
        }
    }
}



4. Copy below web.config code in your web.config



<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
 
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>

    <services>

      <service name="ActiveDirectoryDetails.Service1" behaviorConfiguration="ServiceBehaviour">

        <endpoint address ="" binding="webHttpBinding" contract="ActiveDirectoryDetails.IService1" behaviorConfiguration="web">

        </endpoint>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name="ServiceBehaviour">

          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>

        </behavior>

      </serviceBehaviors>

      <endpointBehaviors>

        <behavior name="web">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="1" />

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  <httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>
  </system.webServer>

</configuration>


5. Create your Client Application and paste below Ajax Call Method



    <script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
      GetUsersDetails();
      function GetUsersDetails() {
          $.ajax({
              url: "http://localhost:80/Service1.svc/GetADUsers/?domain=sfsd&userid=wjrkj&password=4728346",
              data: {
                  format: 'json'
              },
              type: 'GET',
              dataType: 'json',
              success: function (data) {
                  console.log(data.GetADUsersResult);
              }, error: function () {
                  console.log("Error....");
              }
          });
      }
});

</script>
4. Finally below will be result




Thursday, 15 June 2017

Search On ListViewWebPart

Search On ListVIewWebPart Using Javascript

Copy and Paste below given script in CQWP

<script type="text/javascript">
    function RedirectUrl() {
        var tb = document.getElementById("tbSearch").value;
        var cs = document.getElementById("sfield").value;
        var url = "";

        if (tb != "") {
            if (cs == "Column2" || cs == "Column3" || cs == "Column4" || cs == "Column5") {
                url = "FilterField1=" + cs + "&FilterValue1=" + tb;
                window.location.href = "AllItems.aspx?" + url;
            }
            else {
                url = "FilterName=" + cs + "&FilterMultiValue=*" + tb + "*";
                window.location.href = "AllItems.aspx?" + url;
            }
        }
        else {
            return false;
        }
    }
    function ClearUrl() {
        window.location.href = "AllItems.aspx";
    }
        </script>Search Field:
<select id="sfield"><option value="FirstName">FirstName</option><option value="FirstName">LastName</option><option value="Company">Department</option><option value="Email">Email</option></select>   Search text:
<input id="tbSearch" type="text"/><input id="btnSearch" onclick="return RedirectUrl();" type="button" value="Search"/><input id="btnClear" onclick="return ClearUrl();" type="button" value="Clear"/>​​​​​