Pages

Tuesday, January 12, 2016

How to get unique items or values from an Array JQuery

Introduction


There are lots of ways by using programming techniques to filter the array data and get the unique item value(s) out of it. 

In this post, I will show how to filter the array data and get the unique item values from it by using JQuery.

Again, there are many ways to do the same in JQuery but I will show you one of many ways which I find is easy to use and implement.


Prerequisites



Let's get started!


To filter and get the unique items from an array, let's create a variable with a name as "fruits" and it has repeating items in it such as:

var fruits = ["Apple", "Oranges", "Grapes", "Guava", "Mango", "Apple", "Oranges", "Grapes", "Guava", "Mango", "Mango", "Apple", "Mango", "Apple", "Mango", "Apple"];

Now, we want to filter this array and we want unique items from the above array i.e. "Apple", "Oranges", "Grapes", "Guava" and "Mango".

To do the same, we will use .grep() function and .inArray() function of JQuery.

In laymen terms, grep() function is a utility function for arrays to filter out values.It finds the elements of an array which satisfy a filter function. The original array is not affected. 

To know more about JQuery grep() function, please see here http://api.jquery.com/jquery.grep/

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.


To know more about JQuery inArray() function, please see here https://api.jquery.com/jQuery.inArray/.

We will create another variable as "uniqueFruits" and in this variable, we will store all the unique items from the "fruits" variable we created above like this:

var uniqueFruits = $.grep(fruits, function (name, index) {
                return $.inArray(name, fruits) === index;
            }); // Returns Unique fruits

In the above lines of code, we now have all the unique fruits in the "uniqueFruits" variable and we can check the same by using alert function of Javascript or we can also check the same in browser console.

Note: We haven't touched/modified the "fruits" array. It still contains the original repeating fruits values.

Here is the browser console output of "uniqueFruits" variable:

console.log(uniqueFruits);

Gives output as:



Here is the browser alert() output of "uniqueFruits" variable:

alert(uniqueFruits);

Gives output as:


Here is the complete code we have used to filter an array and get a unique values out from it:

<script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
        $(document).ready(function () {
            var fruits = ["Apple", "Oranges", "Grapes", "Guava", "Mango", "Apple", "Oranges", "Grapes", "Guava", "Mango", "Mango", "Apple", "Mango", "Apple", "Mango", "Apple"];

            var uniqueFruits = $.grep(fruits, function (name, index) {
                return $.inArray(name, fruits) === index;
            }); //Returns Unique fruits

            console.log(uniqueFruits); // Or alert(uniqueFruits);          
        });
</script>

In the above lines of code, in the first line, we are referencing to the JQuery CDN library.

In document.ready() function, we are using "fruits" array variable with repeating items in it.

And then by using .grep() and .inArray() function, we are fetching the records from array and checking if it is unique.

If it is unique, we are adding it to "uniqueFruits" variable.


Conclusion


In this post, we have seen how we can get unique items from an array using JQuery.

In my next post, I will share the information on how to get unique values from multidimensional array using JQuery.

Read More »

Saturday, January 9, 2016

JavaScript Invalid Date or NaN in Internet Explorer - Solved

Recently, I faced an issue with Internet Explorer while I was working with Date() function of JavaScript.

This issue occurred when I was passing string which has the date to the JavaScript Date() function and wanted to display it on the page.

My code was this:

  <script type="text/javascript">
       var dateValue = "2016-01-06 00:43:06";
       var date = new Date(dateValue);
       alert(date);
    </script>

When I executed this code in Internet Explorer, I got error as "Invalid Date".


To my surprise, the same code when I executed in Chrome, I got the correct output I was expecting.


After some research, I found that with browsers like Internet Explorer and Safari, we have to pass date string in specific format to the JavaScript Date() function. The browsers like Chrome, Firefox and Opera supports any format.

So, what is the solution for Internet Explorer?


Solution is to modify the format of the string passed in the JavaScript Date() function.

That means, we shouldn't pass the date string to the JavaScript Date() function with "yyyy-mm-dd" or "yyyy-mm-dd hh:mm:ss" format while executing the same in Internet Explorer or Safari. 

The correct formats would be:
"yyyy/mm/dd" or
"yyyy/mm/dd hh:mm:ss" or
"yyyy, mm-1, dd" or
"yyyy, mm-1, dd, hh, mm, ss" or
"mm/dd/yyyy" or
"mm/dd/yyyy hh:mm:ss" or you could use milliseconds as well.

In other words, we can't use dash ("-") in the format for passing date string in the JavaScript Date() function.

To solve the existing problem, I used following code which helped me in getting the correct and expected output in both of my browsers that is Internet Explorer and Chrome.

<script type="text/javascript">
        var dateValue = "2016-01-06 00:43:06";
        var modifiedDateValue = dateValue.split("-"); // Gives Output as 2016,01,06 00:43:06
        var date = new Date(modifiedDateValue[0] + "/" + modifiedDateValue[1] + "/" + modifiedDateValue[2]); // Here, passing the format as "yyyy/mm/dd"    
        alert(date);
    </script>

Here is the output I got from the Internet Explorer:

As you could now see, instead of getting "Invalid Date" or "NaN" error, I got the correct date along with the time I have passed in the date string.

Here is the output I got from the Chrome:

Alternatively, you can also use replace function in the code to replace all the dashes in your date string with forward slash as shown below:

    <script type="text/javascript">
        var dateValue = "2016-01-06 00:43:06";
        var modifiedDateValue = dateValue.replace("-", "/");         
        var date = new Date(modifiedDateValue);
        alert(date);
    </script>

This code will also give the same valid output in Internet Explorer and Chrome along with other browsers as the above code gives.

It is up to your choice of selecting the code which will work for you.

Hope this helps!

Read More »

Friday, January 8, 2016

Hide Save Button From Ribbon In SharePoint

Introduction


Many times in SharePoint we want to perform different things which are not possible by using the available features which SharePoint provides Out of the Box.

Hiding Save button in the SharePoint list forms ribbon is one of them.

Usually, when we create/edit a new item in SharePoint lists, we have two Save buttons available. One is in top ribbon of the page and another one at the end of the form controls.

Let's suppose, we have a scenario where we don't want two save buttons in SharePoint list forms (i.e. in "NewForm.aspx" and "EditForm.aspx").

In this post, I will show you how we can hide Save button from the ribbon of list forms i.e. "NewForm.aspx" and "EditForm.aspx" using simple JQuery code.



Prerequisite


For implementing this functionality, we would require:
  • Basic knowledge of JQuery/JavaScript
  • Basic knowledge of SharePoint such as editing page, adding web part to a page
  • JQuery library reference from the JQuery CDN which we will be adding to our JQuery script


Implementation


So, lets see how we can hide Save button from the list forms ribbon.

Let's suppose, we have a list name as "Test" list as shown below:















We will now go to the "NewForm.aspx" page by clicking on "+ new item" link button and we will hide the below shown "Save" button appearing in the ribbon of "NewForm.aspx" page:
















To do the same, we will edit this "NewForm.aspx" page by clicking on "Site Settings" button and then clicking on "Edit Page" as shown below:



Once "NewForm.aspx" page is in edit mode, we will click on "Add a Web Part" link and then from the "Categories", we will select "Media and Content". Once "Media and Content" category is selected, under the "Parts" section, we will select "Script Editor" and then we will click on "Add" button as shown below:














Now, you have added "Script Editor" web part to your "NewForm.aspx" page, click on "EDIT SNIPPET" link of "Script Editor" web part and write the below line of code in it and click on "Insert" button:

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

<script type="text/javascript">

    $("a[id$='Ribbon.ListForm.Edit.Commit.Publish-Large']").hide();

</script>


As you can see, in the above code, in first line we are referencing to JQuery CDN library. And in third line, we are finding the ID of "Save" button in the ribbon of list form page and then hiding it by using JQuery's hide function.
























Once the code is inserted into the "Script Editor" web part, on top left corner of your page, in the ribbon under "PAGE" tab, click on "Stop Editing" as shown below:




When you click on "Stop Editing" button in a ribbon, you will be redirected to the list's "AllItems.aspx" page.
From there, click on new item link button to navigate to "NewForm.aspx" page or to create a new item for the list. You will notice now in "NewForm.aspx" page, there is no "Save" button displaying in the ribbon as shown below:















So, as you can see by following above steps and using simple JQuery code, we can hide "Save" button appearing in ribbon for "NewForm.aspx" page.

By following the similar steps we did for "NewForm.aspx" page, we can hide "Save" button in"EditForm.aspx" page as well. There will be no changes in the code for hiding the "Save" button in "EditForm.aspx" page.

Conclusion


In this post, we have seen one of many ways to hide "Save" button appearing in the ribbon of list forms for SharePoint list. 








Read More »

Sunday, January 3, 2016

CAML Query Builder for SharePoint Online

Introduction


Folks, you might have seen lots of CAML Query Builder tools available for SharePoint On-premise but when it comes to SharePoint Online, we don't find much of the tools available. 

Even if some tools are available, there are lots of problem in installing or configuring them and to make them work especially for SharePoint Online.

Here, I will be sharing an information with you all on from where we can download the SharePoint CAML Query Builder tool for SharePoint Online and how we can configure it.


Prerequisite


I will be sharing an information on downloading a CAML Query Builder tool called SPCAMLQueryHelper tool which you can download from here https://spcamlqueryhelper.codeplex.com/ and can read more information about the same.

Before installing this tool, following things are required as specified in the link above:

  • .NET Framework 3.5, SharePoint 2013 program version uses 4.5 - Well in the website they have specified about SP2013 program version uses 4.5. This is because if you would like to use this CAML Query Builder tool for SharePoint On-premise. But I have installed it in my laptop which has Windows 7 as OS and Visual Studio 2015 without SP2013 to connect it to SharePoint Online.
  • Run on server with SOM installed - Again, this is required if you want to use it for SharePoint On-premise.


How to download


To download this tool, please follow the steps below:

1. Go to this location - https://spcamlqueryhelper.codeplex.com/

2. On the right hand side of the page, click on 'download' button as shown below: 















3. Clicking on 'download' button will download the '.zip' file folder with name as SPCAMLQueryHelperOnline.exe in the download folder of your machine. 

4. Go to that folder and right click on it and under 7-Zip option, click on 'Extract files' and click on OK. 

In case you do not see this 7-Zip option when you right click on the folder then it means you don't have 7-Zip installed in your machine. You can download the same from this location - http://www.7-zip.org/. Otherwise, if you have different file extracting software installed in your machine such as WinZip or WinRar, you can use them as well.

5. Once the folder extraction is done, you will see a new folder is created with the same name i.e. SPCAMLQueryHelperOnline.exe

Double click on it and inside this folder you will find four files such as:

     a) Microsoft.SharePoint.Client.dll
     b) Microsoft.SharePoint.Client.Runtime.dll
     c) SPCAMLQueryHelperOnline - It is an application file or .exe file
     d) SPCAMLQueryHelperOnline.exe - It is a XML configuration file


If you notice here that your download is complete but there is no setup file as such to install and configure the settings for this SharePoint CAML Query Builder tool to use it for SharePoint Online. 

Let's see how we can configure it.

How to configure

To configure the tool, we have to add both Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll files we have downloaded to the Global Assembly Cache (i.e. GAC)

If you have already installed or have Visual Studio in your machine then you can follow the below steps I have specified to add both the files to GAC. 

You can also see MSDN article on how to install an assembly into the Global Assembly Cache from this location - https://msdn.microsoft.com/en-us/library/dkkx7f79(v=vs.110).


How to add both the files in GAC if you have Visual Studio installed


1. Open Developer Command Prompt - To open the same, Windows + R key in your keyboard and type dev in Run window. It will open developer command prompt. 

If the above step doesn't work, click on Start, expand All Programs, and then expand Microsoft Visual Studio. Depending on the version of Visual Studio you have installed, choose Visual Studio Tools, Visual Studio Command Prompt, or the command prompt you want to use. Make sure to run it as Administrator by right click on it and click on Run as administrator.

Additionally, you can also see MSDN article on how to open Developer Command Prompt from here - https://msdn.microsoft.com/en-us/library/ms229859(v=vs.110).aspx

2. Once command prompt is open, type following command in it:

        gactutil -i C:\your_file_location

For example, my complete file location for Microsoft.SharePoint.Client.dll is C:\Users\Downloads\SPCAMLQueryHelperOnline.exe\Microsoft.SharePoint.Client.dll so my command will be:

      gactutil -i C:\Users\Downloads\SPCAMLQueryHelperOnline.exe\Microsoft.SharePoint.Client.dll



3. Once you have typed in the command as specified above, press 'Enter' key on your keyboard and you will see a message in a command prompt as "Assembly successfully added to the cache".

4. Follow the similar steps to add Microsoft.SharePoint.Client.Runtime.dll file as well to the GAC.

5. Once both the files i.e. Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll  are added to the GAC, now open the SPCAMLQueryHelperOnline application file from the SPCAMLQueryHelperOnline.exe folder which was downloaded along with these two ".dll" files.

6. When you will open the SPCAMLQueryHelperOnline application, you will see three options with radio buttons. 

Select the last option as "Use Web Services (Office 365)". This will enable the "Username" and "Password" text-boxes. Enter your SharePoint Online username (ideally your email address) and password as shown below and click on "SUBMIT" button:




7. Clicking on "SUBMIT" button will open below shown window of this application where under the "Site URL" enter your SharePoint Online site URL and click on "Load":



8. Clicking on "LOAD" button will show all the available lists on your sites to your left side under "Lists" section as shown below:



As you can see in the above step, under the "Lists" section on the left side, all the lists available inside your site will be displayed. To start using CAML Query for a list, double click on the specific list and then click on "Query Helper" tab above the "List Name" text-box. 

To learn on how to use this tool or know more about the same, please check this URL - https://spcamlqueryhelper.codeplex.com/

Conclusion

So, here we have seen how we can download the SP CAML Query Helper tool and configure it to connect with the SharePoint Online. 




Read More »

Monday, December 28, 2015

Check If An Item Exists In SharePoint List

How to check if an item exists in SharePoint list using SPServices?

Pre-requisites:





Solution:


Using below shown SPServices code you can check if an item exists or not in a specific list.

You can use JSOM/REST code as well but that would be an asynchronous call, whereas, SPServices is a synchronous call.

Here, in the CAMLQuery, where I have entered “test”, you can dynamically check for the value coming in from the input box or the textbox of your list "NewForm/EditForm.aspx" page or a control added to your custom page.

This code, you can add to your both list’s “NewForm.aspx” or “EditForm.aspx” and even you can add it to your custom page.

In case, if you are adding it to your “NewForm.aspx” or “EditForm.aspx” then you need to put this inside the “PreSaveAction()” function of SharePoint so that before saving/updating, it can be validated.

To know how to use "PreSaveAction" function, please check it here - https://code.msdn.microsoft.com/office/SharePoint2013-Use-of-a27c804f



Hope this helps!
Read More »

Thursday, August 27, 2015

Cannot connect to the server at this time. Your table cannot be published. - SOLVED

Problem:

While importing data from excel file to SharePoint, user may get below error.


Solution:

This is a issue with permissions a user is having. 

For e.g. if user is having "Contribute" access permission then with “Contribute” access permission level, we don’t have an access to create a list in a site. When we import from excel to SharePoint, SharePoint will create a list and as we do not have a permission to create a list, that’s why user may get this error.

Solution is to elevate your permissions.

Read More »

Wednesday, June 10, 2015

How to display Previous and Next buttons or icons in JQuery Datepicker

Folks,

You must have noticed sometimes while using JQuery datepicker control (which comes from jquery-ui.css file) we get the datepicker control but it doesn't display "Previous" and "Next" buttons or icons as shown below.



The fix is to apply a CSS and display them by using below code.


<style type="text/css">
        .ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span {
            background-image: url("https://your_url_of_the_site/folder_where_images_are_uploaded/ui-icons_ef8c08_256x240.png");
        }
 </style>


Above, you can see I am using a code which apply CSS to your ".aspx" or ".ascx" or ".html" page where you are using this datepicker control.

NoteThe URL I am pointing is to the place where your images are stored. These images are those which comes along with when you download the "jquery-ui" library. In this example, I have stored them in a SharePoint library and I am referencing to them there.

Result comes as shown below after applying the CSS:


Hope this helps!
Read More »

Thursday, May 28, 2015

How to get QueryString from URL using JQuery

QueryString using JQuery

There are lots of ways to get query-string from the web URL by using jQuery but this is the best way I feel to retrieve one or more than one query-strings parameters from the URL.

How to do it?

Let's suppose your URL is http://YourUrl.aspx.

It has 2 query-string parameters i.e. "itemid" and "status".

The parameter "itemid" has value as "1" and parameter "status" has value as "Approve".

So, now your URL will be http://YourUrl.aspx?itemid=1&status=Approve.

In your (document).ready() function, add the code as shown below for the URL which has two query-string parameters (i.e. http://YourUrl.aspx?itemid=1&status=Approve):

  $(document).ready(function () {
            var queryString = new Array();
            if (queryString.length == 0) {
                if (window.location.search.split('?').length > 1) {
                    var params = window.location.search.split('?')[1].split('&');
                    for (var i = 0; i < params.lengthi++) {
                        var key = params[i].split('=')[0];
                        var value = decodeURIComponent(params[i].split('=')[1]);
                        queryString[key] = value;
                    }
                }
            }

            if (queryString["itemid"] != null && queryString["status"] != null) {
                try {
                    alert("Your Item ID is: " + queryString["itemid"] + ", Your Status is:" queryString["status"]);
                }
                catch (e) { }
            }
        });

As you can see that using array variable, we can store more than one query-string parameters and retrieve them by passing their key.

I hope this helps!!

Read More »