Tuesday, September 25, 2018

Upload File JS File

Upload File JS File
==================

'use strict';

jQuery(document).ready(function () {

    // Check for FileReader API (HTML5) support.
    if (!window.FileReader) {
        alert('This browser does not support the FileReader API.');
    }
});

// Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() {

    // Define the folder path for this example.
    var serverRelativeUrlToFolder = '/UserShipment';

    // Get test values from the file input and text input page controls.
    var fileInput = jQuery('#getFile');
    var newName = jQuery('#displayName').val();

    // Get the server URL.
    var serverUrl = _spPageContextInfo.webAbsoluteUrl;

    // Initiate method calls using jQuery promises.
    // Get the local file as an array buffer.
    var getFile = getFileBuffer();
    getFile.done(function (arrayBuffer) {

        // Add the file to the SharePoint folder.
        var addFile = addFileToFolder(arrayBuffer);
        addFile.done(function (file, status, xhr) {

            // Get the list item that corresponds to the uploaded file.
            var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
            getItem.done(function (listItem, status, xhr) {

                // Change the display name and title of the list item.
                var changeItem = updateListItem(listItem.d.__metadata);
                changeItem.done(function (data, status, xhr) {
                    alert('file uploaded and updated');
                });
                changeItem.fail(onError);
            });
            getItem.fail(onError);
        });
        addFile.fail(onError);
    });
    getFile.fail(onError);

    // Get the local file as an array buffer.
    function getFileBuffer() {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(fileInput[0].files[0]);
        return deferred.promise();
    }

    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer) {

        // Get the file name from the file input control on the page.
        var parts = fileInput[0].value.split('\\');
        var fileName = parts[parts.length - 1];

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
                "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                "/add(overwrite=true, url='{2}')",
                serverUrl, serverRelativeUrlToFolder, fileName);

        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });
    }

    // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
    function getListItem(fileListItemUri) {

        // Send the request and return the response.
        return jQuery.ajax({
            url: fileListItemUri,
            type: "GET",
            headers: { "accept": "application/json;odata=verbose" }
        });
    }

    // Change the display name and title of the list item.
    function updateListItem(itemMetadata) {

        // Define the list item changes. Use the FileLeafRef property to change the display name.
        // For simplicity, also use the name as the title.
        // The example gets the list item type from the item's metadata, but you can also get it from the
        // ListItemEntityTypeFullName property of the list.
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
            itemMetadata.type, newName, newName);

        // Send the request and return the promise.
        // This call does not return response content from the server.
        return jQuery.ajax({
            url: itemMetadata.uri,
            type: "POST",
            data: body,
            headers: {
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-type": "application/json;odata=verbose",
                "content-length": body.length,
                "IF-MATCH": itemMetadata.etag,
                "X-HTTP-Method": "MERGE"
            }
        });
    }
}

// Display error messages.
function onError(error) {
    alert(error.responseText);
}

Page Web parts

Page Web parts:
---------------------------------------------------------------

$(document).ready(function(){
  GetBIMResoucesItems();

});



function GetBIMResoucesItems() {

var listname = 'BIMResourceLinks';

var url ="/_api/Web/Lists/GetByTitle('"+listname +"')/Items?$select=LinkType,Title,LinkURL,IsActive&$filter=IsActive eq 1&$orderby=Created desc";
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            //console.log(data.d.results);
            IterateBIMItems(data.d.results);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

function IterateBIMItems(result)
{
  var bimData = [];
  if(result.length > 0)
  {
     for(var i=0 ; i<result.length; i++)
{

   var LinkType = result[i].LinkType;
   var Title    = result[i].Title;
   var LinkURL  = result[i].LinkURL;
       var IsActive = result[i].IsActive;
 
       var objArry={
          LinkType : LinkType,
          Title    : Title,
          LinkURL  : LinkURL,
          IsActive : IsActive
      }
      bimData.push(objArry);
    };
  }
 
  GetLinkHeadingArr(bimData);
}

function GetLinkHeadingArr(objArry)
{
 var heads = ["BIM Resources","Trainings","Important Links"];
 
  for(var i=0 ; i<heads.length; i++)
  {
 //  var objArryFilter = objArry.filter(k=> k.LinkType==heads[i]);
 
   var objArryFilter = objArry.filter(function(k){ return k.LinkType===heads[i]});

 
for(var j=objArryFilter.length-1; j>=3; j--)
var newarr = objArryFilter.splice(j, 1); 
 
 
    CreateBIMHTML(objArryFilter,heads[i]);
  }

}

function CreateBIMHTML(objArryFilter,heads)
{
  var content ="<div class='right_title'>"+heads+"<span></span></div>";
  content +="<div class='list_view'>";
  content +="<ul>";
 
  for(var i=0 ; i<objArryFilter.length; i++)
  { 
    content +="<li><a href='"+objArryFilter[i].LinkURL+"'>"+objArryFilter[i].Title+"</a></li>";
  }
 
 
 
  if(heads ==="BIM Resources")
  {
     var url = _spPageContextInfo.webAbsoluteUrl +"/Lists/BIMResourceLinks/AllItems.aspx?FilterName=LinkType&FilterMultiValue=BIM%20Resources";
     content +="</ul><div class='more_list'><a href="+url+" target='_blank'>More<span>...</span></a></div>"; 
     $('#Bim').append(content);
  }
   
  if(heads ==="Trainings")
  {
     var url = _spPageContextInfo.webAbsoluteUrl +"/Lists/BIMResourceLinks/AllItems.aspx?FilterName=LinkType&FilterMultiValue=Trainings";
     content +="</ul><div class='more_list'><a href="+url+" target='_blank'>More<span>...</span></a></div>"; 
     $('#Traning').append(content);

  }
   
  if(heads ==="Important Links")
  {   
     var url = _spPageContextInfo.webAbsoluteUrl +"/Lists/BIMResourceLinks/AllItems.aspx?FilterName=LinkType&FilterMultiValue=Important%20Links";
     content +="</ul><div class='more_list'><a href="+url+" target='_blank'>More<span>...</span></a></div>"; 
$('#Implink').append(content);
  }
 
  content="";
}




News Announcement Slider webpart

News announcement slider:
-------------------------------------


$(document).ready(function(){

  //$('#s4-bodyContainer').css({"padding-bottom":"0px !important",});

  GetAnnouncements();
 
  var url = _spPageContextInfo.webAbsoluteUrl +"/Lists/Announcements/AllItems.aspx";
  $('#NewsAnn').attr("href",url);
 
 

 


});



function GetAnnouncements() {

var listname = 'Announcements';

var url ="/_api/Web/Lists/GetByTitle('"+listname +"')/Items?$select=Title,Body,BodyText,IsActive&$filter=IsActive eq 1&$orderby=Created desc&$top=5";

    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            //console.log(data.d.results);
            IterateAnnouncementItems(data.d.results);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}
var resultNewsArr = [];
function IterateAnnouncementItems(result)
{

  if(result.length > 0)
  {
     resultNewsArr = result;
     var content="<div class='news_announcements'>";
     for(var i=0 ; i<result.length; i++)
{
     var body = result[i].BodyText;
     if(body.length > 580)
     {
        body = result[i].BodyText.substring(0, 580)+"</div>";
     }


         content +="<div><div class='ann_title'>"+result[i].Title+"</div>";
         content +="<div class='ann_desc'>"+body+"</div></br>";
         content +="<div class='more_list ann_more'><a href='#' onclick='ShowPopup("+i+")'>More <span>...</span></a></div>";

         content +="</div>";
       
     }
      content +="</div>";
     
      $('#announcements').append(content);
     
     
     
      $(function(){
$('.news_announcements').bxSlider({
    controls: false
});


});
  }

}


function ShowPopup(newsIndex)
{
 var bodyHTML = resultNewsArr[newsIndex].BodyText;
 var title = resultNewsArr[newsIndex].Title;
 var newsHtml = "<div><b>"+title+"</b></div><br>" + bodyHTML;

 $('#NewAnnouncement').empty();
 $('#NewAnnouncement').append(newsHtml);
 $('.hover_bkgr_fricc').show();
}


$(document).ready(function(){
$('.hover_bkgr_fricc').click(function(){
// $('.hover_bkgr_fricc').hide();
});
$('.popupCloseButton').click(function(){
$('.hover_bkgr_fricc').hide();
});

});

TOP Navigation Upper Menu bar Dynamic:

 TOP Navigation Upper Menu bar Dynamic:

populating from 4 list, 3 parent list, 4 main navigation list
===============================

$(document).ready(function(){

    GetParentMenu();
 
});


//=============== public variables===========
var parentMenu=[]; var PmenuArray=[]; var FmenuArray=[]; var SmenuArray=[];
//===========================================

//===============Get Parent Menu ============

function GetParentMenu() {
    $().SPServices({
        operation: "GetListItems",
        async: false,
        webURL : "https://team.amat.com/sites/BIM_QA/NewAgsDashboard",
        listName: "TopNavigation",
        CAMLViewFields:"<ViewFields Properties='True' />",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='IsActive' /><Value Type='Integer'>1</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='True'/></OrderBy></Query>",
        completefunc: function (xData, Status){
            ParentMenu (xData, Status);
        }
    });
}

//======================= Get all Navigation content in object array ====================

function ParentMenu(xData, Status)
{
    PmenuArray=[]; var newArray = [];
    $(xData.responseXML).SPFilterNode("z:row").each(function() {
 
        if($(this).attr("ows_ParentMenu"))
        {
            var pMenu=""; var fMenu=""; var sMenu=""; var tMenu=""; var url="";
            pMenu = $(this).attr("ows_ParentMenu").split('#')[1];
   
            if($(this).attr("ows_FirstLevelMenu"))
                fMenu = $(this).attr("ows_FirstLevelMenu").split('#')[1];
       
            if($(this).attr("ows_SecondLevelMenu"))
                sMenu = $(this).attr("ows_SecondLevelMenu").split('#')[1];
         
            if($(this).attr("ows_ThirdLevelMenu"))
                tMenu = $(this).attr("ows_ThirdLevelMenu").split('#')[1];
       
            if($(this).attr("ows_LinkUrl"))
                url = $(this).attr("ows_LinkUrl");

            if($.inArray(pMenu, newArray) == -1)
            {
                newArray.push(pMenu);
               
                var objNewArr = {
                pMenu : pMenu,
                fMenu : fMenu,
                url   : url
                };
                parentMenu.push(objNewArr);
            }
            var objArr = {
                pMenu : pMenu,
                fMenu : fMenu,
                sMenu : sMenu,
                tMenu : tMenu,
                url   : url
            };
            PmenuArray.push(objArr);
        }
    });
    LoopParentMenu();
}


//=============Looping parent Menu and getting sub menu ================

function LoopParentMenu()
{
    var Content = "<ul class='nav navbar-nav'>";
    for(var i=0 ; i<parentMenu.length; i++)
    {
        if(parentMenu[i].fMenu)
        {
            Content += "<li><a href='#' class=''>"+parentMenu[i].pMenu+"<span class='caret'></span></a>";
            Content += LoopFirstLevelMenu(parentMenu[i].pMenu)
            Content += "</li>";
        }
        else
        {
            Content += "<li><a href='"+parentMenu[i].url+"'>"+parentMenu[i].pMenu+"</a></li>";
        }
    }
 

    Content += "</ul>";

    $('#menuDiv').append(Content);
 
}
//=====================================================

// ====================Filter first menu ==============

function FilterfstMenu(menuItem)
{
   // var result = PmenuArray.filter(k => k.pMenu == menuItem);
    var result = PmenuArray.filter(function(k){ return k.pMenu == menuItem});

   
    var fstMenu = []; var newArray = [];
    for(var i=0;i<result.length;i++)
    {
         var valuefMenu = result[i].fMenu;
         var valuesMenu = result[i].sMenu;
         var url        = result[i].url;


        if($.inArray(valuefMenu, fstMenu) == -1)
        {
           fstMenu.push(valuefMenu);
         
           var objArray = {
            fMenu: valuefMenu,
            sMenu: valuesMenu,
            url  : url
           };
           newArray.push(objArray);
        } 
       
         
    }
    return newArray;

}

//====================Looping first level menu for geeting HTML for sencond level menu ===============

function LoopFirstLevelMenu(menuItem)
{
    var fstMenu = FilterfstMenu(menuItem);
   // var result = PmenuArray.filter(k => k.pMenu == menuItem);
    var result = PmenuArray.filter(function(k){ return k.pMenu == menuItem});



    var content = "<ul class='dropdown-menu up_arrow'>";
    for(var i=0 ; i<fstMenu.length; i++)
    {
        if(fstMenu[i].sMenu)
        {
            content += "<li><a href='#'>"+fstMenu[i].fMenu+"<span class='caret'></span></a>";
            content += LoopSencondLevelMenu(fstMenu[i].fMenu,menuItem);          //== getting second level menu.
            content += "</li>";
        }
        else
        {
            content += "<li><a href='"+fstMenu[i].url+"'>"+fstMenu[i].fMenu+"</a></li>";
        }
    }
    content += "</ul>";

    return content;
}

// ====================Filter second lvl menu ===============

function FilterSecMenu(menuItem,pmenu)
{
    //var result  = PmenuArray.filter(k => k.fMenu == menuItem);
    var result  = PmenuArray.filter(function(v,i){return(v["fMenu"] == menuItem) && (v["pMenu"] == pmenu)});
    var scdMenu = []; var newArray = [];

    for(var i=0;i<result.length;i++)
    {
         var valuesMenu = result[i].sMenu;
         var valuetMenu = result[i].tMenu;
         var url        = result[i].url;
     
        if($.inArray(valuesMenu, scdMenu) == -1)
        {
            scdMenu.push(valuesMenu);
           
              var objArray = {
            sMenu: valuesMenu,
            tMenu: valuetMenu,
            url  : url
           };
           newArray.push(objArray);

        }
    }
    return newArray;

}

// ====================looping second level menu ====================

    function LoopSencondLevelMenu(menuItem,pmenu)
    {
        var scdMenu = FilterSecMenu(menuItem,pmenu);
       // var result  = PmenuArray.filter(k => k.fMenu == menuItem);

        var content = "<ul class='dropdown-menu'>";
        for(var i=0 ; i<scdMenu.length; i++)
        {
            if(scdMenu[i].tMenu)
            {
                  content += "<li><a href='#'>"+scdMenu[i].sMenu+"<span class='caret'></span></a>";
                  content += ThirdLevelMenu(scdMenu[i].sMenu,menuItem,pmenu);
                  content += "</li>";

            }
            else
            {
                content += "<li><a href='"+scdMenu[i].url+"'>"+scdMenu[i].sMenu+"</a></li>";
            }
        }
        content += "</ul>";

        return content;
    }

//============== filter third level menu ================
   
   function FilterThirdMenu(smenu,fmenu,pmenu)
   {
      //  var result  = PmenuArray.filter(k => k.sMenu == menuItem);
        var result  = PmenuArray.filter(function(v,i){return(v["fMenu"] == fmenu) && (v["sMenu"] == smenu) && (v["pMenu"] == pmenu)});
        var trdMenu = []; var newArray = [];
        for(var i=0;i<result.length;i++)
        {           
            var valuetMenu = result[i].tMenu;
            var url        = result[i].url;
            if($.inArray(valuetMenu, trdMenu) == -1)
        {
            trdMenu.push(valuetMenu);
           
        var objArray = {
            tMenu: valuetMenu,
            url  : url
            };
            newArray.push(objArray);
        }
        }
      return newArray;
   }

 //================= looping third level menu ==================

   function ThirdLevelMenu(tmenu,smenu,pmenu)
    {
        var trdMenu = FilterThirdMenu(tmenu,smenu,pmenu)
        var content = "<ul class='dropdown-menu'>";
       
        for(var i=0 ; i<trdMenu.length; i++)
        {
            if(trdMenu[i].tMenu)
            {
                content += "<li><a href='"+trdMenu[i].url+"'>"+trdMenu[i].tMenu+"</a></li>";
            }
         
        }
        content += "</ul>";
        return content;
    }

 //===========================================






SP.Service Query To SharePoint Nested Example

SP.service nested Example
--------------------------------

var RequestId = 0;
$(document).ready(function(){


SP.SOD.executeFunc('sp.js', SP.ClientContext, fn_getModuleCategoriesMatrix);
var loaded = 0;
    function fn_LoadNewContext() {
        context = new SP.ClientContext("/sites/coo/");
        web = context.get_web();
        CurrentUserName = $().SPServices.SPGetCurrentUser({fieldName: "Title",debug: false});
}
//
$(".ms-dlgOverlay").show();
function fn_getModuleCategoriesMatrix()
{
try
{
if(loaded == 0)
{
$().SPServices({
operation: "GetListItems",
async: false,
listName: "BU",
completefunc: function (xModules, moduleStatus)
{
if($(xModules.responseXML).SPFilterNode("z:row").length > 0)
{ var changeBuflag = 0;
$(xModules.responseXML).SPFilterNode("z:row").each(function()
{
var BU = $(this).attr("ows_Title");
var BUId = $(this).attr("ows_ID");

$().SPServices({
operation: "GetListItems",
async: false,
listName: "SubSegment",
CAMLQuery:"<Query><Where><Contains><FieldRef Name='BU' /><Value Type='Text'>"+BU +"</Value></Contains></Where></Query>",
completefunc: function (xCategories, categoriesStatus)
{
if($(xCategories.responseXML).SPFilterNode("z:row").length > 0)
{
$(xCategories.responseXML).SPFilterNode("z:row").each(function(){
var SubSegment = $(this).attr("ows_Title");
var SubSegmentId = $(this).attr("ows_ID");

$().SPServices({
operation: "GetListItems",
async: false,
listName: "Product",
CAMLQuery:"<Query><Where><Contains><FieldRef Name='SubSegment' /><Value Type='Text'>"+SubSegment+"</Value></Contains></Where></Query>",
completefunc: function (xProducts, productsStatus)
{
$(xProducts.responseXML).SPFilterNode("z:row").each(function(){
var Product = $(this).attr("ows_Title");
var ProductId = $(this).attr("ows_ID");
var Configuration = $(this).attr("ows_Configuration");
var ListOfApprovers = $(this).attr("ows_ListOfApprovers").split("#");
var SecondaryApprovers = $(this).attr("ows_SecondaryApprovers").split("#");
var sysListOfApprovers = $(this).attr("ows_ListOfApprovers");
var IsActive = $(this).attr("ows_IsActive");

///////////// For primary Approvers//////////
if(IsActive == 1)
{


var listApprovers="", item=0;

for(item = 1;item < ListOfApprovers.length;item = item+2)
{
if(listApprovers == "")
{
listApprovers += ListOfApprovers[item];
}
else
{
listApprovers += " &nbsp;"+ListOfApprovers[item];
}
}
                                 
                                   var approvers = listApprovers.split(" &nbsp;").join('');
                                   var formattedapprovers= approvers.replace(/'/g, "&#39;");

                                 //////////////////For secondary Approvers ///////////
                                 
                                 if(IsActive == 1)
{
var secApprovers="", index=0;
for(index = 1;index < SecondaryApprovers.length;index = index+2)
{
if(secApprovers == "")
{
secApprovers += SecondaryApprovers[index];
}
else
{
secApprovers += " &nbsp;"+SecondaryApprovers[index];
}

}


                                   }
                                 
var secondapprs = secApprovers.split(" &nbsp;").join('');
                                   var formattedsecapprovers= secondapprs.replace(/'/g, "&#39;");

                                 

var rowClass="";

if(changeBuflag == 0)
rowClass = "oddRow";
else
rowClass = "evenRow";

var trString= "<tr class='"+rowClass +"'>";

if(BU.trim()!="")
trString= "<tr class='"+rowClass +"' style='border-top:1px #bdbdbd solid;'>";

trString += "<td><nobr>"+BU +"</nobr></td><td><nobr>"+SubSegment +"</nobr></td><td><nobr>"+Product +"</nobr></td><td>"+Configuration +"</td>";

trString += "<td align='center'><input type='checkbox' id='chk_"+BUId+"_"+SubSegmentId+"_"+ProductId+"' productId='"+ ProductId +"' approvers='"+formattedapprovers+"' secapprovers='"+formattedsecapprovers+"'/>  </td>";

trString += "<td><nobr>"+listApprovers +"</nobr></td>";
trString += "</tr>";
BU ="";
SubSegment = "";
$("#tblRequestAccessMain").append(trString);
}
});
}
});
});
}
}
});
if(changeBuflag ==0)
{
changeBuflag = 1;
}
else
{
changeBuflag = 0;
}
});
}
}
});
        $(".ms-dlgOverlay").hide();


loaded = 1;
}
}
catch(err)
{
        $(".ms-dlgOverlay").hide();
}
}



////////////// Creating New Item in Request Master List/////////////









var tblRequestAccessMain= $("#tblRequestAccessMain");
var checkedProducts =[];
var checkedBU = [];
var checkedSubSegments = [];
var checkedApprovers = [];
var checkedProductNames = [];
var checkedConfiguration =[];
var checkedSecApprovers =[];
var itemIndex = 0;
var Reason ="";
var status = "Pending";





function submitrequest(){

        Reason = $("#txtReasonForRequestAccess").val();
var tblRequestAccessMain = $("#tblRequestAccessMain");

var rowIndex, row, BU, SubSegment, Product, Configuration;
var itemChecked = false;
checkedProducts =[];
for(rowIndex = 2; rowIndex<tblRequestAccessMain[0].rows.length; rowIndex++)
{
row = tblRequestAccessMain[0].rows[rowIndex];

if(row.cells[0].innerText.trim()!="")
BU = row.cells[0].innerText;

if(row.cells[1].innerText.trim()!="")
SubSegment = row.cells[1].innerText;

Product = row.cells[2].innerText;
Configuration = row.cells[3].innerText;

var cellAccess = row.cells[4];

var chkAccess = cellAccess.children[0];

if(chkAccess.checked==true)
{
itemChecked = true;
checkedProducts.push(chkAccess.getAttribute("productid"));
Product
checkedBU.push(BU);
checkedSubSegments.push(SubSegment);
checkedConfiguration.push(Configuration);
checkedApprovers.push(chkAccess.getAttribute("approvers"));
checkedSecApprovers.push(chkAccess.getAttribute("secapprovers"));
checkedProductNames.push(Product);

}
}


if(itemChecked!=true && Reason!="")
{
$(".ms-dlgOverlay").hide();
alert("Please select atleast one product to send access request.")
return false;
}

if(itemChecked==true && Reason=="")
{
$(".ms-dlgOverlay").hide();
alert("Please specify role, organization, manager, and reason for request.")
return false;
}

if(itemChecked!=true && Reason=="")
{
$(".ms-dlgOverlay").hide();
alert("Please select atleast one product and specify reason to send access request.")
return false;
}




   var message ="Access request sent succesfully for:\n";
   var errormessage ="Request already pending for the following items,\n";
var count =0;
   var bu;
   var product;
   var subsegment;
   var approvers;
   var secapprovers
   var name;
var configuration;
 
for(var itemIndex = 0; itemIndex < checkedProducts.length;itemIndex++)
   {
 
    bu = checkedBU[itemIndex];
    product = checkedProductNames[itemIndex];
    subsegment = checkedSubSegments[itemIndex];
    configuration = checkedConfiguration[itemIndex];
   
    name;
 
 
 
    $().SPServices({
operation: "GetListItems",
async: false,
listName: "poc",
CAMLQuery:"<Query><Where><And><And><And><Eq><FieldRef Name='RequestedBy'/><Value Type='Text'>"+CurrentUserName+"</Value></Eq><Eq><FieldRef Name='Product'/><Value Type='Text'>"+product+"</Value></Eq></And><Eq><FieldRef Name='Configuration'/><Value Type='Text'>"+configuration+"</Value></Eq></And><Eq><FieldRef Name='status'/><Value Type='Text'>"+status+"</Value></Eq></And></Where></Query>",

completefunc: function (xData, Status)
{
if($(xData.responseXML).SPFilterNode("z:row").length>0)
       
{
errormessage += bu+ "-->"+subsegment+"-->"+product+"-->"+configuration+"\n";
count++;


}
}
 
});
   
   }
if (count > 0)
{

$(".ms-dlgOverlay").hide();
alert(errormessage);

 tblRequestAccessMain;
checkedProducts =[];
checkedBU = [];
checkedSubSegments = [];
checkedApprovers = [];
checkedProductNames = [];
checkedConfiguration =[];
    checkedSecApprovers =[];


return false;
}

else {

 
for(var Index = 0; Index < checkedProducts.length;Index++)
   {
 
    bu = checkedBU[Index];
    product = checkedProductNames[Index];
    subsegment = checkedSubSegments[Index];
    approvers = checkedApprovers[Index];
    configuration = checkedConfiguration[Index];
    secapprovers = checkedSecApprovers[Index];
    name;
 
 
    $().SPServices({
            operation: "UpdateListItems",
            async: false,
            batchCmd: "New",
            listName: "poc",
            valuepairs: [["BU", bu],["Reason",Reason],["ListofApprovers" , approvers],["SubSegment" , subsegment],["Product" , product],["status" , status],["RequestedBy",CurrentUserName],["Configuration",configuration],["SecondaryApprovers",secapprovers]],
            completefunc: function (xData, Status) {
                message += bu+ "-->"+subsegment+"-->"+product+"-->"+configuration+"\n";
               
            }
         
        });

   
   }

alert(message);
window.location.href = window.location.href;
}

}



$(".btnRequest").click(function(){
$(".ms-dlgOverlay").show();
//pausecomp(10000);
submitrequest();

});




function pausecomp(millis)
{
  var date = new Date();
  var curDate = null;
  do { curDate = new Date(); }
  while(curDate-date < millis);
}
});










JavaScript Utilities validation

JavaScript utilities:
--------------------------

amatJSUtil = function () { }
//
amatJSUtil.roundTo2Decimals = function (numberToRound, isNecessaryCheck) {
    if (isNecessaryCheck && isNecessaryCheck == true) {
        if (numberToRound.toString().split('.')[1])
            return Number(numberToRound).toFixed(2);
        else
            return numberToRound;
    }
    else {
        return Number(numberToRound).toFixed(2);
    }
}
//
amatJSUtil.roundTo1Decimals = function (numberToRound, isNecessaryCheck) {
    if (isNecessaryCheck && isNecessaryCheck == true) {
        if (numberToRound.toString().split('.')[1])
            return Number(numberToRound).toFixed(1);
        else
            return numberToRound;
    }
    else {
        return Number(numberToRound).toFixed(1);
    }
}
//
amatJSUtil.replaceAll = function (str, replace, with_this) {
    var str_hasil = "";
    var temp;
    for (var i = 0; i < str.length; i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
            temp = with_this;
        else
            temp = str[i];

        str_hasil += temp;
    }
    return str_hasil;
}
//
amatJSUtil.getFileName = function (path) {
    var ary = amatJSUtil.replaceAll(path, "/", "\\").split("\\");
    return ary[ary.length - 1];
}
//
amatJSUtil.zeroPad = function (number, width) {
    z = '0';
    number = number + '';
    return number.length >= width ? number : new Array(width - number.length + 1).join(z) + number;
}
//
amatJSUtil.isValidDate = function (date) {
    var valid = true;

    date = amatJSUtil.replaceAll(date, '/', '');

   
    var month = parseInt(date.substring(0, 2), 10);
    var day = parseInt(date.substring(2, 4), 10);
    var year = parseInt(date.substring(4, 8), 10);
   
    var extra = date.substring(8, date.length);

    if (isNaN(year) || isNaN(month) || isNaN(day) || extra.trim() != '') {
        valid = false;
    } else {
        if ((month < 1) || (month > 12))
            valid = false;
        else if ((day < 1) || (day > 31))
            valid = false;
        else if (((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30))
            valid = false;
        else if ((month == 2) && (((year % 400) == 0) || ((year % 4) == 0)) && ((year % 100) != 0) && (day > 29))
            valid = false;
        else if ((month == 2) && ((year % 100) == 0) && (day > 29))
            valid = false;
    }
    return valid;
}
//
amatJSUtil.validateEmail = function (email) {
    var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
    if (reg.test(email)) {
        return true;
    }
    else {
        return false;
    }
}
//
amatJSUtil.isValidDateOnPaste = function (e, obj) {

    var valid = true;
    var date;
    if (e) {
        date = e.clipboardData.getData('Text');
    } else {
        date = window.clipboardData.getData('Text');
    }
    date = amatJSUtil.replaceAll(date, '/', '');

    var year = parseInt(date.substring(0, 4), 10);
    var month = parseInt(date.substring(4, 6), 10);
    var day = parseInt(date.substring(6, 8), 10);
    var extra = date.substring(8, date.length);

    if (isNaN(year) || isNaN(month) || isNaN(day) || extra.trim() != '') {
        valid = false;
    } else {
        if ((month < 1) || (month > 12))
            valid = false;
        else if ((day < 1) || (day > 31))
            valid = false;
        else if (((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30))
            valid = false;
        else if ((month == 2) && (((year % 400) == 0) || ((year % 4) == 0)) && ((year % 100) != 0) && (day > 29))
            valid = false;
        else if ((month == 2) && ((year % 100) == 0) && (day > 29))
            valid = false;
    }
    if (!valid)
        alert("Enter Valid Date");

    return valid;
}
amatJSUtil._decimalNumberOnly = function (e, obj) {
    var dotlength = obj.value.split('.').length;
    var dotlArray = obj.value.split('.');
    var unicode;
    if (e) {
        unicode = e.charCode ? e.charCode : e.keyCode;
    } else {
        unicode = event.charCode ? event.charCode : event.keyCode;
    }
    //
    if (unicode != 8) { //if the key isn't the backspace key (which we should allow)
        if (((unicode < 48 || unicode > 57) && unicode != 46) || (unicode == 46 && dotlength >= 2)) //obj.value.split(".").length>=3) ) //if not a number
            return false //disable key press
    }
}
//
amatJSUtil._decimalNumberTwoPrecisionOnly = function (e, obj) {
    var dotlength = obj.value.split('.').length;
    var dotlArray = obj.value.split('.');
    var unicode;
    if (e) {
        unicode = e.charCode ? e.charCode : e.keyCode;
    } else {
        unicode = event.charCode ? event.charCode : event.keyCode;
    }
    //
    if (unicode != 8) { //if the key isn't the backspace key (which we should allow)
        if (((unicode < 48 || unicode > 57) && unicode != 46) || (unicode == 46 && dotlength >= 2)) //obj.value.split(".").length>=3) ) //if not a number
            return false //disable key press
        else if (dotlength == 2 && dotlArray[1].length > 2) {
            return false;
        }
    }
}
//
amatJSUtil._decimalNumTwoPrecisionPaste = function (e, obj) {
    var totalCharacterCount;
    if (e) {
        totalCharacterCount = e.clipboardData.getData('Text');
    } else {
        totalCharacterCount = window.clipboardData.getData('Text');
    }

    var strValidChars = "0123456789";
    var strDot = ".";
    var strChar;
    var FilteredChars = "";
    var isDotPresent = 0;
    for (i = 0; i < totalCharacterCount.length; i++) {
        strChar = totalCharacterCount.charAt(i);
        if (strValidChars.indexOf(strChar) != -1) {
            FilteredChars = FilteredChars + strChar;
        }
        if (strDot.indexOf(strChar) != -1 && isDotPresent == 0) {
            FilteredChars = FilteredChars + strChar;
            isDotPresent = 1;
        }
    }
    if (isDotPresent == 1) {
        obj.value = Number(FilteredChars).toFixed(2);
    }
    else {
        obj.value = Number(FilteredChars);
    }

    amatJSUtil.currencyMask(obj);

    return false;
}

amatJSUtil._decimalNumPaste = function (e, obj) {
    var totalCharacterCount;
    if (e) {
        totalCharacterCount = e.clipboardData.getData('Text');
    } else {
        totalCharacterCount = window.clipboardData.getData('Text');
    }

    var strValidChars = "0123456789";
    var strDot = ".";
    var strChar;
    var FilteredChars = "";
    var isDotPresent = 0;
    for (i = 0; i < totalCharacterCount.length; i++) {
        strChar = totalCharacterCount.charAt(i);
        if (strValidChars.indexOf(strChar) != -1) {
            FilteredChars = FilteredChars + strChar;
        }
        if (strDot.indexOf(strChar) != -1 && isDotPresent == 0) {
            FilteredChars = FilteredChars + strChar;
            isDotPresent = 1;
        }
    }
    obj.value = Number(FilteredChars);
    amatJSUtil.currencyMask(obj);
    return false;
}
//
amatJSUtil._integerNumbersOnly = function (e, obj) {
    var unicode;
    if (e) {
        unicode = e.charCode ? e.charCode : e.keyCode;
    } else {
        unicode = event.charCode ? event.charCode : event.keyCode;
    }
    //
    if (unicode != 8) { //if the key isn't the backspace key (which we should allow)
        if (unicode < 48 || unicode > 57) //obj.value.split(".").length>=3) ) //if not a number
            return false //disable key press
    }
}
amatJSUtil._integerCurrencyOnly = function (e, obj) {
    var unicode;
    if (e) {
        unicode = e.charCode ? e.charCode : e.keyCode;
    } else {
        unicode = event.charCode ? event.charCode : event.keyCode;
    }
    //
    if (unicode != 8) { //if the key isn't the backspace key (which we should allow)
        if (unicode < 48 || unicode > 57) //obj.value.split(".").length>=3) ) //if not a number
            return false //disable key press
    }
}

//
amatJSUtil._integerNumPaste = function (e, obj) {
    var totalCharacterCount;
    if (e) {
        totalCharacterCount = e.clipboardData.getData('Text');
    } else {
        totalCharacterCount = window.clipboardData.getData('Text');
    }

    var strValidChars = "0123456789";
    var strChar;
    var FilteredChars = "";
    for (i = 0; i < totalCharacterCount.length; i++) {
        strChar = totalCharacterCount.charAt(i);
        if (strValidChars.indexOf(strChar) != -1) {
            FilteredChars = FilteredChars + strChar;
        }
    }
    obj.value = FilteredChars;
    return false;
}
amatJSUtil._integerCurrencyPaste = function (e, obj) {
    var totalCharacterCount;
    if (e) {
        totalCharacterCount = e.clipboardData.getData('Text');
    } else {
        totalCharacterCount = window.clipboardData.getData('Text');
    }

    var strValidChars = "0123456789";
    var strChar;
    var FilteredChars = "";
    for (i = 0; i < totalCharacterCount.length; i++) {
        strChar = totalCharacterCount.charAt(i);
        if (strValidChars.indexOf(strChar) != -1) {
            FilteredChars = FilteredChars + strChar;
        }
    }
    obj.value = FilteredChars;
    amatJSUtil.currencyMask(obj);
    return false;
}

amatJSUtil.currencyMask = function (obj) {
    //if(event.keyCode != 37 && event.keyCode != 39)
    {
        var amtString = (obj.value).split(".")[0];
        var amtString = AddComma(amatJSUtil.replaceAll(amtString, ",", ""));
        if ((obj.value).split(".").length >= 2)
            amtString = amtString + "." + (obj.value).split(".")[1];
        obj.value = amtString;
    }
}
function AddComma(MyString) {
    var objRegex = new RegExp('(-?[0-9]+)([0-9]{3})');
    //Check For Criteria....
    while (objRegex.test(MyString)) {
        //Add Commas After Every Three Digits Of Number...
        MyString = MyString.replace(objRegex, '$1,$2');
    }
    return MyString;
}
//
//#Region " Object Identification Methods "
amatJSUtil.getInputTypeText = function (title, id) {
    return (($("input[title='" + title + "']")[0]) ? $("input[title='" + title + "']")[0] : $("input[id*='" + id + "']")[0])
}
//
amatJSUtil.getInputTypeTextAll = function (id) {
    return ($("input[id*='" + id + "']"));
}
amatJSUtil.getInputTypeButtonById = function (id) {
    return ($("input[id*='" + id + "']")[0]);
}

//
amatJSUtil.getInputTypeOpenDecimalNumberText = function (title, id) {
    var objTextBox = (($("input[title='" + title + "']")[0]) ? $("input[title='" + title + "']")[0] : $("input[id*='" + id + "']")[0])
    objTextBox.style.textAlign = "right";
    objTextBox.value = amatJSUtil.replaceAll(objTextBox.value, ",", "");
    objTextBox.maxLength = 21;
    //$("input[id*='" + id + "']").mask("999,999,999,999,999.00");
    objTextBox.onkeypress = function (e) {
        return amatJSUtil._decimalNumberOnly(e, this);
    }
    objTextBox.onpaste = function (e) {

        //return amatJSUtil._decimalNumPaste(e, this);
        return false;
    }
    objTextBox.ondrag = function (e) {
        return false;
    }
    objTextBox.ondrop = function (e) {
        return false;
    }
    return objTextBox;
}
//
amatJSUtil.getInputTypeDecimalNumberText = function (title, id) {
    var objTextBox = (($("input[title='" + title + "']")[0]) ? $("input[title='" + title + "']")[0] : $("input[id*='" + id + "']")[0])
    objTextBox.style.textAlign = "right";
    objTextBox.value = amatJSUtil.replaceAll(objTextBox.value, ",", "");
    objTextBox.maxLength = 21;
    //$("input[id*='" + id + "']").mask("999,999,999,999,999.00");
    objTextBox.onkeypress = function (e) {
        return amatJSUtil._decimalNumberTwoPrecisionOnly(e, this);
    }
    objTextBox.onpaste = function (e) {
        return false;
        //return amatJSUtil._decimalNumTwoPrecisionPaste(e, this);
    }
    objTextBox.ondrag = function (e) {
        return false;
    }
    objTextBox.ondrop = function (e) {
        return false;
    }
    return objTextBox;
}
//
amatJSUtil.getInputTypeIntegerCurrencyText = function (title, id) {
    var objTextBox = (($("input[title='" + title + "']")[0]) ? $("input[title='" + title + "']")[0] : $("input[id*='" + id + "']")[0])
    objTextBox.style.textAlign = "right";
    objTextBox.value = amatJSUtil.replaceAll(objTextBox.value, ",", "");
    objTextBox.maxLength = 21;

    objTextBox.onkeypress = function (e) {
        return amatJSUtil._integerCurrencyOnly(e, this);
    }
    objTextBox.onpaste = function (e) {
        return false;
        //return amatJSUtil._integerCurrencyPaste(e, this);
    }
    objTextBox.ondrag = function (e) {
        return false;
    }
    objTextBox.ondrop = function (e) {
        return false;
    }

    return objTextBox;
}

amatJSUtil.getInputTypeIntegerNumberText = function (title, id) {
    var objTextBox = (($("input[title='" + title + "']")[0]) ? $("input[title='" + title + "']")[0] : $("input[id*='" + id + "']")[0])
    objTextBox.style.textAlign = "right";
    objTextBox.value = amatJSUtil.replaceAll(objTextBox.value, ",", "");

    objTextBox.onkeypress = function (e) {
        return amatJSUtil._integerNumbersOnly(e, this);
    }
    objTextBox.onpaste = function (e) {
        return false;
        //return amatJSUtil._integerNumPaste(e, this);
    }
    objTextBox.ondrag = function (e) {
        return false;
    }
    objTextBox.ondrop = function (e) {
        return false;
    }

    return objTextBox;
}
//
amatJSUtil.getSelectType = function (title, id) {
    return (($("select[title='" + title + "']")[0]) ? $("select[title='" + title + "']")[0] : $("select[id*=" + id + "]")[0])
}
//
amatJSUtil.getSelectTypeAll = function (id) {
    return ($("select[id*=" + id + "]"));
}
//
amatJSUtil.getTextAreaType = function (title, id) {
    return (($("textarea[title='" + title + "']")[0]) ? $("textarea[title='" + title + "']")[0] : $("textarea[id*=" + id + "]")[0])
}
//
amatJSUtil.getTextAreaTypeAll = function (title, id) {
    return ($("textarea[id*=" + id + "]"));
}
//
amatJSUtil.getDivType = function (title, id) {
    return (($("div[title='" + title + "']")[0]) ? $("div[title='" + title + "']")[0] : $("div[id$='" + id + "']")[0]);
}
//
amatJSUtil.getDivTypeAll = function (title, id) {
    return (($("div[title='" + title + "']")) ? $("div[title='" + title + "']") : $("div[id$='" + id + "']"));
}
//#endregion

Tuesday, September 18, 2018

A Very Simple Popup Box – HTML, CSS, JavaScript

https://html-online.com/articles/simple-popup-box/

j query reference:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>


Popup boxes are the most useful way of showing a warning or any other important information to the website visitors in many HTML5 templates. In this article I’m going to walk you through the creation of a very simple popup box with shadow overlay and close button. We’re going to implement this using HTML, CSS and jQuery in less than 100 lines (not compressed code).
simple popup box html css js

The box and the shadow is hidden when the page loads, we have to trigger an event, like a link click to show it.
Use the iframe below to test the live demo:

The HTML Code

Add a link that triggers the box and a div that behaves like the box shadow. This wraps the actual box with the close button. The helper span is used to center the box vertically.
<a class="trigger_popup_fricc">Click here to show the popup</a>

<div class="hover_bkgr_fricc">
    <span class="helper"></span>
    <div>
        <div class="popupCloseButton">X</div>
        <p>Add any HTML content<br />inside the popup box!</p>
    </div>
</div>

The CSS Code

/* Popup box BEGIN */
.hover_bkgr_fricc{
    background:rgba(0,0,0,.4);
    cursor:pointer;
    display:none;
    height:100%;
    position:fixed;
    text-align:center;
    top:0;
    width:100%;
    z-index:10000;
}
.hover_bkgr_fricc .helper{
    display:inline-block;
    height:100%;
    vertical-align:middle;
}
.hover_bkgr_fricc > div {
    background-color: #fff;
    box-shadow: 10px 10px 60px #555;
    display: inline-block;
    height: auto;
    max-width: 551px;
    min-height: 100px;
    vertical-align: middle;
    width: 60%;
    position: relative;
    border-radius: 8px;
    padding: 15px 5%;
}
.popupCloseButton {
    background-color: #fff;
    border: 3px solid #999;
    border-radius: 50px;
    cursor: pointer;
    display: inline-block;
    font-family: arial;
    font-weight: bold;
    position: absolute;
    top: -20px;
    right: -20px;
    font-size: 25px;
    line-height: 30px;
    width: 30px;
    height: 30px;
    text-align: center;
}
.popupCloseButton:hover {
    background-color: #ccc;
}
.trigger_popup_fricc {
    cursor: pointer;
    font-size: 20px;
    margin: 20px;
    display: inline-block;
    font-weight: bold;
}
/* Popup box BEGIN */

The Script

$(window).load(function () {
    $(".trigger_popup_fricc").click(function(){
       $('.hover_bkgr_fricc').show();
    });
    $('.hover_bkgr_fricc').click(function(){
        $('.hover_bkgr_fricc').hide();
    });
    $('.popupCloseButton').click(function(){
        $('.hover_bkgr_fricc').hide();
    });
});