Friday, 21 July 2017

Table Column Sorting

Column Sorting


<td style="text-align:center">
<span id="proj-filter" index=3 class="pointer">Auditor Status</span>
</td>


f_project *= -1;
    var n = $("#projectsort").prevAll().length;
    var n=3;---index value of td

    sortTable(f_project,n);



function sortTable(f,n){
var rows = $('#analystdashboardid tbody  tr').get();

rows.sort(function(a, b) {

var A = getVal(a);
var B = getVal(b);

if(A < B) {
return -1*f;
}
if(A > B) {
return 1*f;
}
return 0;
});

function getVal(elm){
var v = $(elm).children('td').eq(n).text().toUpperCase();
if($.isNumeric(v)){
v = parseInt(v,10);
}
return v;
}

$.each(rows, function(index, row) {
$('#analystdashboardid').children('tbody').append(row);
});
}

Pagination using javascript and Jquery

Pagination
Html
<script type="text/javascript">
var pager = new Pager('analystdashboardid', 10);
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);

</script>


Js

function Pager(tableName, itemsPerPage) {
debugger;
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
{
this.showPage(this.currentPage - 1);
}
else
{
alert('No records');
}
}
this.next = function() {
if (this.currentPage<this.pages) {
this.showPage(this.currentPage + 1);
}
else
{
alert('No records');
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> Prev </span> ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next </span>';
element.innerHTML = pagerHtml;
}
}


Individual Columns Filter in a Table


Individual Columns Filter in a Table
 Add this lines  in page load:

$("#analystdashboardid thead td #proj-filter").click(function(){

     showFilterOption(this);
    });



/*Individual columns filter */
var arrayMap = {};
var ArrayDuplicate=new Array();
var SelectedValues=new Array();
function showFilterOption(tdObject){
debugger;
  var filterGrid = $(tdObject).find(".filter");
  ArrayDuplicate.length=0;
  if (filterGrid.is(":visible")){
    filterGrid.hide();
    return;
  }

  $(".filter").hide();

  var index = 0;
  filterGrid.empty();
  var allSelected = true;
  filterGrid.append('<div><input id="all" type="checkbox" checked class="excelhidespan">Select All</div>');

  var $rows = $(tdObject).parents("table").find("tbody tr");


  $rows.each(function(ind, ele){

    var currentTd = $(ele).children()[$(tdObject).attr("index")];
    var div = document.createElement("div");
    div.classList.add("grid-item")
    var str = $(ele).is(":visible") ? 'checked' : '';
    if ($(ele).is(":hidden")){
      allSelected = false;
    }
 
    var currentTdValue=currentTd.innerHTML;
    var dummyArray = $.grep(ArrayDuplicate, function(dt) {
    return dt== currentTdValue;
    });
    if(dummyArray.length==0)
    {
     div.innerHTML = '<input type="checkbox" '+str+' class="excelhidespan" >'+currentTd.innerHTML;
     filterGrid.append(div);
     ArrayDuplicate.push(currentTd.innerHTML);
    }
    else
    {
      div.innerHTML = '<input type="checkbox" class="excelhidespan">'+currentTd.innerHTML;
      div.style.display = 'none';
      filterGrid.append(div);
    }
    arrayMap[index] = ele;
    index++;
  });

  if (!allSelected){
    filterGrid.find("#all").removeAttr("checked");
  }

  filterGrid.append('<div><input id="close" type="button" value="Close"/><input id="ok" type="button" value="Ok"/></div>');
  filterGrid.show();

  var $closeBtn = filterGrid.find("#close");
  var $okBtn = filterGrid.find("#ok");
  var $checkElems = filterGrid.find("input[type='checkbox']");
  var $gridItems = filterGrid.find(".grid-item");
  var $all = filterGrid.find("#all");

  $closeBtn.click(function(){

    filterGrid.hide();
    return false;
  });

  $okBtn.click(function(){

    SelectedValues.length=0;
    filterGrid.find(".grid-item").each(function(ind,ele){
      if ($(ele).find("input").is(":checked")){
        SelectedValues.push($(ele)[0].textContent);
      }
    });
    filterGrid.find(".grid-item").each(function(ind,ele){
 
      var dummyArray1 = $.grep(SelectedValues, function(dt) {
      return dt== $(ele)[0].textContent;
      });
      if(dummyArray1.length>0)
      {
        $(arrayMap[ind]).show();
      }
      else{
        $(arrayMap[ind]).hide();
      }
    });
    filterGrid.hide();
    return false;
  });

  $checkElems.click(function(event){

    event.stopPropagation();
    //return false;
  });

  $gridItems.click(function(event){

    var chk = $(this).find("input[type='checkbox']");
    $(chk).prop("checked",!$(chk).is(":checked"));
  });

  $all.change(function(){

    var chked = $(this).is(":checked");
    filterGrid.find(".grid-item [type='checkbox']").prop("checked",chked);
  })

  filterGrid.click(function(event){

    event.stopPropagation();
    //return false;
  });

  return filterGrid;
}

Get Current login User details

var UserID= _spPageContextInfo.userId;

function GetCurrentloginUser()
{
 var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + UserID+ ")";
 var requestHeaders = { "accept" : "application/json;odata=verbose" };
 $.ajax({
   url : requestUri,
   contentType : "application/json;odata=verbose",
   headers : requestHeaders,
   success : onSuccess,
   error : onError
 });
}

/* Function to get currently logged on user name for On Success */

function onSuccess(data, request){

  var name = data.d.LoginName.split('|')[2];
  loginusername=name.split('@')[0]

}

/* Function to alert an error message on Error */

function onError(error) {
  alert(error);
}

Get all users email and populate autocomplete

Get all users email and populate autocomplete 

 Getalluseremails(Getalluseremailssuccess,Getalluseremailsfailure);

$("#frmaddressid").autocomplete({
//minLength: 0,
source: useremaillist
});

$("#Rplyaddressid").autocomplete({
//minLength: 0,
source: useremaillist
});

$( "#audiencesizeid" )
      // don't navigate away from the field on tab when selecting an item
      .on( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).autocomplete( "instance" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        minLength: 1,
        source: function( request, response ) {
          // delegate back to autocomplete, but extract the last term
          response( $.ui.autocomplete.filter(
            useremaillist, extractLast( request.term ) ) );
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
/* Multiple user selection in a textarea separated by ','*/
  function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }



Get all users email 

function Getalluseremails()
{

$.ajax({
   url : _spPageContextInfo.webAbsoluteUrl + "/_api/Web/SiteUsers",
   type : "GET",
   headers:{ "Accept": "application/json; odata=verbose" },
   success:function (data) {
   Getalluseremailssuccess(data.d.results)},
   error:function(jqxr,errorCode,errorThrown){
       alert(jqxr.responseText);
   }

});
}

/* Function to get all user email id's on Success */

function Getalluseremailssuccess(emailarray)
{


if(emailarray.length>0)
{
for(var i=0;i<emailarray.length;i++)
{
userEmailList.push(emailarray[i].Email);    
}
}
}

/* Function to get all user email id's on Failure */

function Getalluseremailsfailure()
{
// Do Nothing

}



Getting Mobile Number From Share Point user Profile

// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.

var userProfileProperties;
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {

   // Make sure PeopleManager is available

   SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', function() {

       // get the target users domain name and account name.

    var targetUser = "i:0#.f|membership|inspiredata@gbtmarketingreview.onmicrosoft.com";

    // Get the current client context.

    var clientContext = new SP.ClientContext.get_current();

    //Get PeopleManager Instance

    var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);

    // Get the properties to retrieve

    var profilePropertyNames = ["AccountName", "FirstName","LastName","Assistant", "Office","Personal site","WorkPhone", "Mobilephone","CellPhone","Fax","Department" ];

    var userProfilePropertiesForUser = new SP.UserProfiles.UserProfilePropertiesForUser(
    clientContext,
    targetUser,
    profilePropertyNames);

    // Get user profile properties for the target user

    userProfileProperties =peopleManager.getUserProfilePropertiesFor(userProfilePropertiesForUser);

    // Load the UserProfilePropertiesForUser object.

    clientContext.load(userProfilePropertiesForUser)

    //Execute the Query

    clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
   });

});




// This function runs if the executeQueryAsync call succeeds.

function onRequestSuccess() {

    var messageText = "\" AccountName \" property is "
    + userProfileProperties[0];
    messageText += "<br />\" FirstName \" property is "
    + userProfileProperties[1];
    messageText += "<br />\" LastName \" property is "
    + userProfileProperties[2];
    messageText += "<br />\" Assistant \" property is "
    + userProfileProperties[3];
    messageText += "<br />\" Office \" property is "
    + userProfileProperties[4];
    messageText += "<br />\" Personal site \" property is "
    + userProfileProperties[5];
    messageText += "<br />\" HomePhone \" property is "
    + userProfileProperties[6];
    messageText += "<br />\" Mobilephone \" property is "
    + userProfileProperties[7];
    messageText += "<br />\" CellPhone \" property is "
    + userProfileProperties[8];
    messageText += "<br />\" Fax \" property is "
    + userProfileProperties[9];
    messageText += "<br />\" Department \" property is "
    + userProfileProperties[10];
 alert("WorkPhone"+userProfileProperties[6])
    $get("Display").innerHTML = messageText;
}

// This function runs if the executeQueryAsync call fails.

function onRequestFail(sender, args) {

    $get("Display").innerHTML = "Error: " + args.get_message();
}

Sharepoint ListItems(Get,Delete)


Get Item From Sharepoint List

var siteURL=site url of user.
var Listname=sharepoint list name.

function GetItems(Success,Failure)
{
$.ajax(
{

url: siteURL+"/_api/web/lists/getbytitle('Listname')/items?",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (data) {
Success(data.d.results);
},
error: function (data) {
}    
});
}

function GetItemsSuccess(arrayvalues)
{
alert('Success');
}
function GetItemsFailure()
{
alert('failure');
}

Delete Item From Sharepoint List

var DocId=20;
function DeleteListitem()
{
$.ajax({
    url:siteUrl+ "/_api/web/lists/GetByTitle('Listname')/items('+DocId+')",
    type: "POST",
    headers: {
               "Accept": "application/json;odata=verbose",
               "content-type": "application/json; odata=verbose",
               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
               "X-HTTP-Method": "DELETE",
               "If-Match": "*"
              } ,
    success: function(data)
        //alert("Item deleted successfully!");
      },
    error: function(err){
      //alert("Error while deleting item: " + JSON.stringify(err));
    }    
});
}

Tuesday, 18 July 2017

Export the HTML table to excel is not working in IE+ Mozilla & Chrome

Export the HTML table to excel is not working in IE+ Mozilla & Chrome:

function fnExcelReport()
        {
                 var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
                 var textRange; var j=0;
              tab = document.getElementById('headerTable'); // id of table


              for(j = 0 ; j < tab.rows.length ; j++) 
              {     
                    tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
                    //tab_text=tab_text+"</tr>";
              }

              tab_text=tab_text+"</table>";
              tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
              tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
                          tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

                   var ua = window.navigator.userAgent;
                  var msie = ua.indexOf("MSIE "); 

                     if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
                        {
                               txtArea1.document.open("txt/html","replace");
                               txtArea1.document.write(tab_text);
                               txtArea1.document.close();
                               txtArea1.focus(); 
                                sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
                              }  
                      else                 //other browser not tested on IE 11
                          sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  


                          return (sa);
                                }

Just Create a blank iframe:

<iframe id="txtArea1" style="display:none"></iframe>

button click:
<button id="btnExport" onclick="fnExcelReport();"> EXPORT 
            </button>

refer:http://stackoverflow.com/questions/22709029/export-the-html-table-to-excel-is-not-working-in-ie

Get Version History Details From share point document Library using Rest api


Using rest api :
site URL+"/_api/web/lists/get by title (List Name)/items$expand=File/Versions",


  • if we use up to (/_api/web/lists/get by title(List Name)/items) it gives all the details from list/library
  • If You want all details about particular document we need to use Expand query using expand key word
  • In side file versions available so that need to expand versions.

site URL    : Its site url .
List Name  : share-point list/library name.

Using Ajax with Rest api:

$.ajax(
{
url:site URL+"/_api/web/lists/get by title(List Name)/items$expand=File/Versions,"
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (data) {
Success(data.d.results);
},
error: function (data) {
}    
});
}

How to get the value from web.config(if any value assign as static Key)

Web.Config File:   <appSettings>     <add key="DomainName" value="PW" />     </appSettings> Cl...