JavaScript Archives : Binary Bits https://blog.binarybits.net/category/web/javascript/ Bits & Pieces - A blog by Kannan Balasubramanian Mon, 03 May 2021 10:50:10 +0000 en-GB hourly 1 https://wordpress.org/?v=6.5.2 Get query string parameter using JavaScript https://blog.binarybits.net/get-query-string-parameter-using-javascript/ https://blog.binarybits.net/get-query-string-parameter-using-javascript/#respond Tue, 18 Jul 2017 06:40:39 +0000 https://blog.binarybits.net/?p=924 Following code will help in fetching the value of a query string parameter. function GetQueryStringParameter(parameter) { var search = location.search.substring(1); var queryStringParameters = JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}') return queryStringParameters[parameter]; } Usage: If URL is http://server/page.html?id=1 Then usage would be GetQueryStringParameters(“id”) which would return 1

The post Get query string parameter using JavaScript appeared first on Binary Bits.

]]>
Following code will help in fetching the value of a query string parameter.

function GetQueryStringParameter(parameter) {
    var search = location.search.substring(1);
    var queryStringParameters = JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
    return queryStringParameters[parameter];
}

Usage:

If URL is http://server/page.html?id=1

Then usage would be GetQueryStringParameters(“id”) which would return 1

The post Get query string parameter using JavaScript appeared first on Binary Bits.

]]>
https://blog.binarybits.net/get-query-string-parameter-using-javascript/feed/ 0
Remove duplicate list items from SharePoint REST call result using JavaScript https://blog.binarybits.net/remove-duplicate-list-items-from-sharepoint-rest-call-result-using-javascript/ https://blog.binarybits.net/remove-duplicate-list-items-from-sharepoint-rest-call-result-using-javascript/#respond Wed, 17 May 2017 07:31:10 +0000 https://blog.binarybits.net/?p=861 The following code snippet show how to remove duplicate list items in the JSON result of a SharePoint REST call using JavaScript. Function Definition: function RemoveDuplicateItems(items, propertyName) { var result = []; if (items.length > 0) { $.each(items, function (index, item) { if ($.inArray(item[propertyName], result) == -1) { result.push(item); } }); } return result; } […]

The post Remove duplicate list items from SharePoint REST call result using JavaScript appeared first on Binary Bits.

]]>
The following code snippet show how to remove duplicate list items in the JSON result of a SharePoint REST call using JavaScript.

Function Definition:

function RemoveDuplicateItems(items, propertyName) {
    var result = [];
    if (items.length > 0) {
        $.each(items, function (index, item) {
            if ($.inArray(item[propertyName], result) == -1) {
                result.push(item);
            }
        });
    }
    return result;
}

Function Usage:
In the below code, assumption is that, the REST call returns data.d.results and the column for which duplicate items need to be removed is Title

var items = data.d.results;
items = RemoveDuplicateItems(items, 'Title');

 

The post Remove duplicate list items from SharePoint REST call result using JavaScript appeared first on Binary Bits.

]]>
https://blog.binarybits.net/remove-duplicate-list-items-from-sharepoint-rest-call-result-using-javascript/feed/ 0
Pass multiple parameters in SetTimeout JavaScript Function https://blog.binarybits.net/pass-multiple-parameters-in-settimeout-javascript-function/ https://blog.binarybits.net/pass-multiple-parameters-in-settimeout-javascript-function/#respond Wed, 17 May 2017 07:24:11 +0000 https://blog.binarybits.net/?p=859 Following is a code snippet which show how to pass multiple parameters in JavaScript’s SetTimeout() function. setTimeout(function () { CustomFunction(param1, param2, param3, param4, param5); }, 1000);

The post Pass multiple parameters in SetTimeout JavaScript Function appeared first on Binary Bits.

]]>
Following is a code snippet which show how to pass multiple parameters in JavaScript’s SetTimeout() function.

setTimeout(function () {
    CustomFunction(param1, param2, param3, param4, param5);
}, 1000);

The post Pass multiple parameters in SetTimeout JavaScript Function appeared first on Binary Bits.

]]>
https://blog.binarybits.net/pass-multiple-parameters-in-settimeout-javascript-function/feed/ 0
Refresh web part without refreshing page in SharePoint https://blog.binarybits.net/refresh-web-part-without-refreshing-page-sharepoint/ https://blog.binarybits.net/refresh-web-part-without-refreshing-page-sharepoint/#respond Tue, 16 May 2017 09:34:30 +0000 https://blog.binarybits.net/?p=850 The following code shows how to refresh web part without refreshing page in SharePoint. // Set Ajax refresh context var eventAjax = { currentCtx: ctx, csrAjaxRefresh: true }; // Initiate Ajax Refresh on the list AJAXRefreshView(eventAjax, SP.UI.DialogResult.OK); Source: https://pradiprathod.wordpress.com/2015/05/04/how-to-refresh-list-view-in-sharepoint-2013-using-javascript/

The post Refresh web part without refreshing page in SharePoint appeared first on Binary Bits.

]]>
The following code shows how to refresh web part without refreshing page in SharePoint.

// Set Ajax refresh context
var eventAjax = {
    currentCtx: ctx,
    csrAjaxRefresh: true
};
// Initiate Ajax Refresh on the list
AJAXRefreshView(eventAjax, SP.UI.DialogResult.OK);

Source: https://pradiprathod.wordpress.com/2015/05/04/how-to-refresh-list-view-in-sharepoint-2013-using-javascript/

The post Refresh web part without refreshing page in SharePoint appeared first on Binary Bits.

]]>
https://blog.binarybits.net/refresh-web-part-without-refreshing-page-sharepoint/feed/ 0
Load scripts in SharePoint within custom Javascript or Workflow https://blog.binarybits.net/load-scripts-sharepoint-within-custom-javascript-workflow/ https://blog.binarybits.net/load-scripts-sharepoint-within-custom-javascript-workflow/#respond Thu, 11 May 2017 05:08:03 +0000 https://blog.binarybits.net/?p=844 Following is the code which can be used to load JavaScript in sequence. This code for example loads the reputation.js from SharePoint’s layouts folder & jQuery from site assets. (function () { ExecuteOrDelayUntilScriptLoaded(function () { //sp.runtime.js has been loaded ExecuteOrDelayUntilScriptLoaded(function () { //sp.js has been loaded SP.SOD.registerSod('reputation.js', SP.Utilities.Utility.getLayoutsPageUrl('reputation.js')); SP.SOD.registerSod('jquery-3.2.1', '../SiteAssets/Scripts/jquery-3.2.1.min.js'); SP.SOD.loadMultiple(['reputation.js', 'jquery-3.2.1'], function () { […]

The post Load scripts in SharePoint within custom Javascript or Workflow appeared first on Binary Bits.

]]>
Following is the code which can be used to load JavaScript in sequence.

This code for example loads the reputation.js from SharePoint’s layouts folder & jQuery from site assets.

(function () {
    ExecuteOrDelayUntilScriptLoaded(function () {
        //sp.runtime.js has been loaded
        ExecuteOrDelayUntilScriptLoaded(function () {
            //sp.js has been loaded
            SP.SOD.registerSod('reputation.js', SP.Utilities.Utility.getLayoutsPageUrl('reputation.js'));
            SP.SOD.registerSod('jquery-3.2.1', '../SiteAssets/Scripts/jquery-3.2.1.min.js');
            SP.SOD.loadMultiple(['reputation.js', 'jquery-3.2.1'], function () {
                //reputation.js & jquery-3.2.1.min.js have been loaded.
                var context = SP.ClientContext.get_current();
                var web = context.get_web();
                //Check if jQuery has been loaded
                if (typeof jQuery != 'undefined') {
                    console.log("Jquery is loaded");
                }
                else {
                    console.log("Jquery is not loaded!");
                }
            });
        }, "sp.js");
    }, "sp.runtime.js");
})();

Source: https://sharepoint.stackexchange.com/questions/92082/uncaught-typeerror-cannot-read-property-get-current-of-undefined

The post Load scripts in SharePoint within custom Javascript or Workflow appeared first on Binary Bits.

]]>
https://blog.binarybits.net/load-scripts-sharepoint-within-custom-javascript-workflow/feed/ 0
File Icons in SharePoint Search Results using Display Template https://blog.binarybits.net/file-icons-sharepoint-search-results-using-display-template/ https://blog.binarybits.net/file-icons-sharepoint-search-results-using-display-template/#respond Mon, 11 Jul 2016 05:44:37 +0000 https://blog.binarybits.net/?p=777 In SharePoint 2013 search results, the icon for a file type like .msg, .txt shows up as .html icon. In SharePoint 2010 this was overcome by mapping the icon file type in DocIcon.xml at WFE Servers. But now since access to WFE servers are restricted in on-prem environment and no access in O-365 environment, the […]

The post File Icons in SharePoint Search Results using Display Template appeared first on Binary Bits.

]]>
In SharePoint 2013 search results, the icon for a file type like .msg, .txt shows up as .html icon.
In SharePoint 2010 this was overcome by mapping the icon file type in DocIcon.xml at WFE Servers.

But now since access to WFE servers are restricted in on-prem environment and no access in O-365 environment, the only solution available is to do the following.

  1. Edit the existing display template (I use custom display template with results shown in table and following is based on that) or create a new template for existing for the following located at (SiteCollection/All Files/_catalogs/masterpage/Display Templates/Search) accessible by using SharePoint Designer.
    1. xxxSearchTableResults.html
    2. xxxSearchTableItem.html
  2. Add the following codes and it should show correct icons.

Search Results Display Template:

<div style="width:15px;display:table-cell;text-align:left;font-weight:bold;padding: 5px 0px 4px 10px;">                                       
</div>

Search Item Display Template:

<div style="min-width:16px;max-width:16px;display: table-cell;white-space:nowrap;overflow:hidden;-ms-text-overflow:ellipsis;-o-text-overflow:ellipsis;text-overflow:ellipsis;">                                       
<!--#_
 var extObj = new Object();
extObj["FileExtension"] = ctx.CurrentItem.FileExtension;
 var iconUrl = SP.Utilities.HttpUtility.htmlEncode(Srch.U.ensureAllowedProtocol(Srch.U.getIconUrlByFileExtension(extObj, null)));
if(ctx.CurrentItem.IsContainer)
iconUrl = "/_layouts/15/images/icdocset.gif";
if(ctx.CurrentItem.FileExtension === "msg")
iconUrl = "/_layouts/15/images/icmsg.gif";
//console.log(ctx.CurrentItem.FileExtension);
 _#-->
<img id="_#= $htmlEncode(id + Srch.U.Ids.icon) =#_" onload="this.style.display='inline'" src='_#= iconUrl =#_' />
 </div>

Notes:
ctx.CurrentItem.FileExtension always return the file extension name which seems to match with the file name in the /_layouts/15/images/ folder.

For example msg = icmsg.gif or icmsg.png

Once done, the search results will show-up as following

Search-Icon

The post File Icons in SharePoint Search Results using Display Template appeared first on Binary Bits.

]]>
https://blog.binarybits.net/file-icons-sharepoint-search-results-using-display-template/feed/ 0
Execute Custom JavaScript code in SharePoint Content Editor webpart https://blog.binarybits.net/execute-custom-javascript-code-sharepoint-content-editor-webpart/ https://blog.binarybits.net/execute-custom-javascript-code-sharepoint-content-editor-webpart/#respond Tue, 22 Mar 2016 07:36:00 +0000 https://blog.binarybits.net/?p=752 When we try to execute a custom java script code in SharePoint content editor web part, it may not work. The reason behind is that, there might be a conflict occurring during load. Microsoft provides ways to launch your function after full page load and following is one of the method. <script type="text/javascript"> _spBodyOnLoadFunctionNames.push("LaunchCustomCode"); LaunchCustomCode […]

The post Execute Custom JavaScript code in SharePoint Content Editor webpart appeared first on Binary Bits.

]]>
When we try to execute a custom java script code in SharePoint content editor web part, it may not work. The reason behind is that, there might be a conflict occurring during load.

Microsoft provides ways to launch your function after full page load and following is one of the method.

<script type="text/javascript">
    _spBodyOnLoadFunctionNames.push("LaunchCustomCode");
    LaunchCustomCode = function() {
		ExecuteOrDelayUntilScriptLoaded(MyCode, "sp.js");
	}

	MyCode = function() {
	console.log('My Code Start');
        alert('MyCode Called');
        console.log('My Code Finish');
	}

</script>

The post Execute Custom JavaScript code in SharePoint Content Editor webpart appeared first on Binary Bits.

]]>
https://blog.binarybits.net/execute-custom-javascript-code-sharepoint-content-editor-webpart/feed/ 0
Add count to drop down refiners in SharePoint search refinement webpart https://blog.binarybits.net/add-count-to-drop-down-refiners-in-sharepoint-search-refinement-webpart/ https://blog.binarybits.net/add-count-to-drop-down-refiners-in-sharepoint-search-refinement-webpart/#respond Thu, 10 Mar 2016 11:43:06 +0000 https://blog.binarybits.net/?p=747 While working on designing display template for drop down based refiners in SharePoint Search there was a requirement to show counts along with refiners in refiners list. Following is the change which I made in the refiner’s display template. Actual code <option value='_#= onChangeOrClick =#_'>_#= $htmlEncode(refinementName) =#_</option>  Updated Code <option value='_#= onChangeOrClick =#_'>_#= $htmlEncode(refinementName) =#_ […]

The post Add count to drop down refiners in SharePoint search refinement webpart appeared first on Binary Bits.

]]>
While working on designing display template for drop down based refiners in SharePoint Search there was a requirement to show counts along with refiners in refiners list.

Following is the change which I made in the refiner’s display template.

Actual code

<option value='_#= onChangeOrClick =#_'>_#= $htmlEncode(refinementName) =#_</option>

 Updated Code

<option value='_#= onChangeOrClick =#_'>_#= $htmlEncode(refinementName)  =#_  (_#= refinementCount =#_)</option>

The post Add count to drop down refiners in SharePoint search refinement webpart appeared first on Binary Bits.

]]>
https://blog.binarybits.net/add-count-to-drop-down-refiners-in-sharepoint-search-refinement-webpart/feed/ 0
Hide Available Refiners in SharePoint search refinement panel https://blog.binarybits.net/hide-available-refiners-in-sharepoint-search-refinement-panel/ https://blog.binarybits.net/hide-available-refiners-in-sharepoint-search-refinement-panel/#respond Tue, 08 Mar 2016 10:37:02 +0000 https://blog.binarybits.net/?p=737 Recently one of the customer had a strange request where the customer wanted to Hide “Available Refiners” in SharePoint search refinement panel. The “Available Refiners” is available in “Drop Down” type refinement panel. When the refinement panel is being loaded, SharePoint executes a JavaScript function named AddPostRenderCallback. This would be available in the Refinement Display […]

The post Hide Available Refiners in SharePoint search refinement panel appeared first on Binary Bits.

]]>
Recently one of the customer had a strange request where the customer wanted to Hide “Available Refiners” in SharePoint search refinement panel.

The “Available Refiners” is available in “Drop Down” type refinement panel.

SharePoint Refinement Panel

When the refinement panel is being loaded, SharePoint executes a JavaScript function named AddPostRenderCallback. This would be available in the Refinement Display Template located under MasterPage/Search Gallery. The actual method looks like below code which is taken from O365.

AddPostRenderCallback(ctx, function() {
    if (hasAnyFiltertokens) {
        // Get the hidden block
        var hiddenOptions = document.getElementById(hiddenBlockID).children;
        var unSelGroup = document.getElementById(unselDD);
        var selGroup = document.getElementById(selDD);
        // Clone all the elements from the hidden list to the unselected option group
        for (var i = 0; i < hiddenOptions.length; i++) {
            var selectedElm = GetAllElementsWithAttribute(selGroup, 'value', hiddenOptions[i].getAttribute('value').replace('updateRefinersJSON', 'removeRefinementFiltersJSON'));
            if (selectedElm === null || selectedElm.length <= 0) {
                var cloneElm = hiddenOptions[i].cloneNode(true);
                unSelGroup.appendChild(cloneElm);
            }
        }
    }
});

To the above original code I made a small change so that “Clone all the elements” code executes only when user has selected a refiner.

// Clone all the elements from the hidden list to the unselected option group
if(selectedFilters.length <= 0)
{
	for (var i = 0; i < hiddenOptions.length; i++) {
		var selectedElm = GetAllElementsWithAttribute(selGroup, 'value', hiddenOptions[i].getAttribute('value').replace('updateRefinersJSON', 'removeRefinementFiltersJSON'));
		if (selectedElm === null || selectedElm.length <= 0) {
			var cloneElm = hiddenOptions[i].cloneNode(true);
			unSelGroup.appendChild(cloneElm);
		}
	}
}

To the above orignal code I added the following code to hide the “Available Refiners” option.

if(selectedFilters.length > 0)
{
	if(unSelGroup!=null)
	{
		unSelGroup.style.display = 'none';
	}
}

The above code will hide the “unSelGroup”‘s “Option Group” HTML to hide the Options for “Available Refiners”.

Final code would look like below.

AddPostRenderCallback(ctx, function() {
    if (hasAnyFiltertokens) {
        // Get the hidden block
        var hiddenOptions = document.getElementById(hiddenBlockID).children;
        var unSelGroup = document.getElementById(unselDD);
        var selGroup = document.getElementById(selDD);
        // Clone all the elements from the hidden list to the unselected option group
        if(selectedFilters.length <= 0)
        {
            for (var i = 0; i < hiddenOptions.length; i++) {
                var selectedElm = GetAllElementsWithAttribute(selGroup, 'value', hiddenOptions[i].getAttribute('value').replace('updateRefinersJSON', 'removeRefinementFiltersJSON'));
                if (selectedElm === null || selectedElm.length <= 0) {
                    var cloneElm = hiddenOptions[i].cloneNode(true);
                    unSelGroup.appendChild(cloneElm);
                }
            }
        }
        //Added for Gold Asset requirement where once a refiner is selected the "Avaialble Refiners" item should be made hidden
        if(selectedFilters.length > 0)
        {
            if(unSelGroup!=null)
            {
                unSelGroup.style.display = 'none';
            }
        }
        
        var refinerUpArrow = document.getElementById('refinerExpandCollapseArrow');
        if(refinerUpArrow!=null)
        {
            refinerUpArrow.style.display = 'none';
        }
        
    }
});

End Result is following
Hidden Available Refiners Option Group

The post Hide Available Refiners in SharePoint search refinement panel appeared first on Binary Bits.

]]>
https://blog.binarybits.net/hide-available-refiners-in-sharepoint-search-refinement-panel/feed/ 0
Clear SharePoint Search Results https://blog.binarybits.net/clear-sharepoint-search-results/ https://blog.binarybits.net/clear-sharepoint-search-results/#respond Mon, 07 Mar 2016 08:33:57 +0000 https://blog.binarybits.net/?p=734 Recently I had a requirement for OOTB search Box + Result where the customer wanted to clear the search results regardless of any refinement selected or not. To implement this, in the display template HTML the following was added. Do note that if refinements are there, the commented single line of code didn’t work and […]

The post Clear SharePoint Search Results appeared first on Binary Bits.

]]>
Recently I had a requirement for OOTB search Box + Result where the customer wanted to clear the search results regardless of any refinement selected or not.

Clear SharePoint Search Results

To implement this, in the display template HTML the following was added.

Do note that if refinements are there, the commented single line of code didn’t work and I had to replace the entire # as blank. Do check the original source (mentioned below) for more information.

<!--#_
    clearSearchResults = function()
    {
        var hash = window.location.hash;
        if( hash.indexOf('Default') == 1 ) {
            hash = unescape(hash);
            var kIdx = hash.indexOf('"k":'); 
            var rIdx = hash.indexOf('","'); 
            var query = hash.substring(kIdx+5,rIdx);
            query = query.replace(/\\/g, '');
            //window.location.href = window.location.pathname + window.location.search + '#k=' + escape(query);
            window.location.href = window.location.pathname + window.location.search + '#';
        } else {
            window.location.href = window.location.pathname + window.location.search + "#";
        }                    
    }
_#-->
<div id="ClearSearch" class="ms-alignCenter">
    <h2><a onclick="clearSearchResults();"  style="cursor:pointer">Clear/Reset All</a></h2>
</div>

The source for the above code is Add a “Clear Filters” link to your search page in SharePoint 2013

The post Clear SharePoint Search Results appeared first on Binary Bits.

]]>
https://blog.binarybits.net/clear-sharepoint-search-results/feed/ 0