Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, August 8, 2017

How To CheckIn And CheckOut a SharePoint page using JavaScript(JSOM)

Hi Friends,

Recently I have come across a requirement where I need to update the properties of a Sharepoint page. In this post we are going to see how to checkin and checkout a page in sharepoint using JSOM.
Below are the code snippets.

CheckOut:
function checkOut(){
        var ctx = SP.ClientContext.get_current();
        var page = ctx.get_web().getFileByServerRelativeUrl(window.location.pathname);
        //you can use any path. Here I am using current page.
        page.checkOut();
        ctx.load(page);
        ctx.executeQueryAsync(Function.createDelegate(this, checkOut_Success),
                                            Function.createDelegate(this, checkOut_Fail));
}
function checkOut_Success(sender, args){
 alert("Checked Out");
//do your actions
}
function checkOut_Fail(sender, args){
   alert("Fail checkout");
}

CheckIn:
function checkIn(){
         var ctx = SP.ClientContext.get_current();
        var web = ctx.get_web();
        var page = web.getFileByServerRelativeUrl(window.location.pathname);   
        //you can use any path. Here I am using current page.  
        page.checkIn();
        page.publish();
        ctx.executeQueryAsync(Function.createDelegate(this, checkIn_Success),
                                            Function.createDelegate(this, checkIn_Fail));
}
function checkIn_Success(sender, args){       
    alert(" checked in "); 
}
function checkIn_Fail(sender, args){   
    alert("Fail  checked in "+args.message);
}

Hope this helps...

Monday, August 7, 2017

How to Copy/Move a SharePoint Page/File from one location to another using Javascript

Hi Friends,

In this blog we are going to see How to copy or move a sharepoint Page/File from one location to the other using Javascript.

By default SP.js in SharePoint provides the following functions through which we can perform this activity with the minimal coding effort.

SP.MoveCopyUtil.copyFile
SP.MoveCopyUtil.moveFile

Copy a Sharepoint File/Page:
In the below code snippet we are copying the home.aspx present in pages library to the Folder called "duplicate" under the same pages library.

In order to achieve it, we will be using the function SP.MoveCopyUtil.copyFile which expects the below parameters

1)Current context
2)Source url – Full url of the file/page.
3)Destination url – Full destination url of the file/Page.

Code snippet:
var current_context = SP.ClientContext.get_current();
SP.MoveCopyUtil.copyFile(current_context,"https://siteurl/pages/home.aspx","http://siteurl/Pages/duplicate/home.aspx");
current_context.executeQueryAsync(function(){ PageCopySuccess(); },function(){ PageCopyFailure(); });

function PageCopySuccess(){
alert('Success');
}

function PageCopyFailure(){
alert('Failed');
}


Move a Sharepoint File/Page:
In the below code snippet we are moving the home.aspx present in pages library to the sitepages page library.

In order to achieve it, we will be using the function SP.MoveCopyUtil.moveFile which expects the below parameters

1)Current context
2)Source url – Full url of the file/page.
3)Destination url – Full destination url of the file/Page.

Code snippet:
var current_context = SP.ClientContext.get_current();
SP.MoveCopyUtil.moveFile(current_context,"https://siteurl/pages/home.aspx","http://siteurl/sitepages/home.aspx");
current_context.executeQueryAsync(function(){ PageMoveSuccess(); },function(){ PageMoveFailure(); });

function PageMoveSuccess(){
alert('Success');
}

function PageMoveFailure(){
alert('Failed');
}

Hope this helps...


Wednesday, March 8, 2017

Why Javascript works only after launching developer tool bar in IE once

Hi Friends,

This post basically talks about the strange experience which I faced in one of the applications.

Problem Statement:
In Internet Explorer, the Javascript/jQuery is not working until I open the IE Tool bar once.


Solution:
After multiple trial and errors, what I observed is, it's because of the console.log present in my jQuery file.

The console object will only be activated when the IE Dev Toolbar is opened. Prior to that, calling the console object will result as undefined. After the toolbar has been opened, the console will exist (even if the toolbar is subsequently closed), so your console calls will then work.


Hence make sure to remove any Console entries from the JS file during the roll-out of the application.


Hope this helps...

Wednesday, February 22, 2017

Open and Close a SharePoint modal dialog with HTML structure

HI Friends,

In this post we are going look at How to Open and Close a SharePoint Modal Dialog using HTML instead of webpage.

Generally we use SharePoint modal dialog in order to call a webpage as pop-in. But, in this post we are going to open a DIV as a pop-in using SharePoint modal dialogue SP.UI.ModalDialog.showModalDialog

Note: You can open any HTML structure as per your needs.

Please use the below code snippet which does this trick.

function OpenModaldialog() {
  SP.SOD.executeOrDelayUntilScriptLoaded(function () {
    var element = document.createElement('div');
    element.innerHTML = '<div id="modalcontent">This is modal dialogue cocntent</div>';

    SP.UI.ModalDialog.showModalDialog({
     html: element,
     title: 'Dialogue box',
     allowMaximize: false,
     showClose: true,
     dialogReturnValueCallback : Function.createDelegate(null, CloseCallback),
     autoSize: true
    });
   }, "SP.js");
}

function CloseCallback(result, target) {
   //custom action if any
}

That's it, you just need to call the function OpenModaldialog(); on the onclick event of the button through which you want to launch the modal dialogue.

Hope this helps...

RELATED POST: How to Show and Hide a Modal Pop up Dialog in a SharePoint
RELATED POST: How to Open and Close a jquery dialog popup

Thursday, May 14, 2015

Add Asset picker(Browse and select file) control to Textbox in a Sharepoint list form Or Page

Hi Guys,

In this post we are going to learn How to add Asset picker control to a SharePoint FORM/Page.

Recently I came across a requirement where user needs to add the reference of a document present in a document library while adding a new list item. As Sharepoint doesn't provide you any OOTB column/field control to pick the asset from the site, User has to go the document library select the particular document then copy shortcut and finally paste the copied URL into List form.

Some of the users do not like this behavior when they have the file already present in document library and expects the option of browse and pick behavior.

In this post we will be adding the "browse and pick file" control to any Textbox box field(of List form) in which you wants to save the URL of the file.

Below are the steps which does the trick.

Step 1:
Create a js file called "createassetpickercontrol.js"

Step 2:
Add the following snippet to the "createassetpickercontrol.js"
$(document).ready(function () {

// With the below line we will be dynamically adding the Browse control next to the textbox where we need to place this. 

//Replace "controlid" with your actual id of the textbox.

$("textarea#controlid").closest('td').append("<div id='btnbrowsectrl' style='display:none'><input onclick='GetFileURL()' type='button' value='Browse File' /><span>Browse File location if exists on same site</span></div>");

 //The below snippet to acheive the browse functionality
//Create a object which will be used for the Asset. I have used the object name as 'assetPickerObj'
    with(new AssetPickerConfig('assetPickerObj'))
    {{
         DefaultAssetImageLocation='';
         //CurrentWebBaseUrl will be the url of the site or site collection.
         CurrentWebBaseUrl='https://siteurl.com';
         OverrideDialogFeatures='';
         OverrideDialogTitle='';
         OverrideDialogDesc='';
         OverrideDialogImageUrl='';
         //AssetUrlClientID is the id of the control in which the path of the selected file will be saved.
         AssetUrlClientID='controlid';
         AssetTextClientID='';                                                             
         UseImageAssetPicker=false; //make this false to show Documents instead
         DefaultToLastUsedLocation=true;
         DisplayLookInSection=true;                                                            
         ReturnCallback = null;}}
});

function GetFileURL(){
    //Following is the function which launch the AssetPortalBrowser.aspx automatically.
    APD_LaunchAssetPickerUseConfigCurrentUrl('assetPickerObj');

//the above line will just give you the relative url to the textbox.
//set absolute url in textbox if required then use the below lines
var newabsoluteurl= window.location.protocol + "//" + window.location.host+$("#controlid ").val().replace(/\s+/g,"%20");
$("#controlid").val(newabsoluteurl);

return false;

}

Step 3: 
Upload the above JS to your site.

Step 4:
Go to the List and then Select default New Form as shown below.

Add a HTML Form webpart and then add the below JS references in it and then Save the page.
AssetPicker.js is a sharepoint farm JS file and will be available in layouts folder. The folder structure will change from 2007 to 2010 environment.

<script src="/_layouts/1033/AssetPickers.js" type="text/javascript"></script>
<script src="/Style%20Library/Scripts/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="/Style%20Library/Scripts/createassetpickercontrol.js" type="text/javascript"></script>

There you go, you could now see the browse button to pick the file url when you open the LIst form as below.

Hope this helps...

Sunday, January 5, 2014

Update User Profile property through jQuery SPServices

Hi folks,
In this post we are going to update User Profile property through jQuery SPServices. Below is the code snippet which does the trick.
Just call the function with the parameters CurrentUserAccountName, PropertyName and PropertyValue.

// add the ref of jQuery file
<script type="text/javascript" src="/style library/jquery-1.7.2.js"></script>
// add the ref of jQuery SPServices file
<script type="text/javascript" src="/style library/jquery.SPServices-0.7.0.min.js"></script>

function updateUserProfile(currUserAccName, propertyName, propertyValue) {
   var propertyData = "<PropertyData>" +
  "<IsPrivacyChanged>false</IsPrivacyChanged>" +
  "<IsValueChanged>true</IsValueChanged>" +
  "<Name>" + propertyName + "</Name>" +
  "<Privacy>NotSet</Privacy>" +
  "<Values><ValueData><Value xsi:type=\"xsd:string\">" + propertyValue + "</Value></ValueData></Values>" +
  "</PropertyData>";

   $().SPServices({
       operation: "ModifyUserPropertyByAccountName",
       async: false,
       webURL: "/",
       accountName: currUserAccName,
       newData: propertyData,
       completefunc: function (xData, Status) {
           var result = $(xData.responseXML);
           if (Status == "success") {
              //success message if needed
           }
       }
   });


}

Hope this helps...

Tuesday, September 24, 2013

Javascript Launch compose new email on button click

Hi Folks,
In this post we are going to see, how to launch compose new email page of your default mail client.
Below is the javascript which will do the trick. You just need to call this function on onclick property of the button present in your webpage.
In this example we will be adding the body of the mail as "{document url}" and subject as "My Subject"
Here we go..

<script type="text/javascript">
function mailThisMsg()
{
var recpt = ""
var subj = "My Subject"
var text = encodeURIComponent(document.URL)
var bcc = ""
var content = new Array()  
content[0] = "mailto:"
content[1] = recpt
content[2] = "?subject="
content[3] = subj
content[4] = "&body="
content[5] = text
content[6] = "&bcc="
content[7] = bcc
content = content.join("")
window.location = content
}
</script>


Hope this helps...

JavaScript Back to Previous Page functionality on a button click

Hi Pals,
In this post we are going to see How to go back to previous page using Javascript on click of anchor button.

Below is the script which will take you to the previous page upon clicking on Back to previous page button.

<a href="#" onClick="history.go(-1)"> Back to Previous Page </a>

Wednesday, May 15, 2013

jQuery SPServices to get current user sharepoint groups

In this post we are going to get information of all the sharepoint user groups in which current user belongs using SPServices.

Below is the jQuery code snippet which will do this action.
In this example we will be looping all the groups which the current user is present and adding it to the variable  loggedinUserGroup.

// add the ref of jQuery file
<script type="text/javascript" src="/style library/jquery-1.7.2.js"></script>
// add the ref of jQuery SPServices file
<script type="text/javascript" src="/style library/jquery.SPServices-0.7.0.min.js"></script>
<script type="text/javascript">
var loggedinUserGroup;
$(document).ready(function() {
 Getrolesforuser();
 alert(loggedinUserGroup);
});
function Getrolesforuser()
{
 loggedinUserGroup="";
 $().SPServices({ 
  operation: "GetGroupCollectionFromUser", 
        userLoginName: $().SPServices.SPGetCurrentUser(), 
        async: false, 
        completefunc: function(xData, Status)
        {
         $(xData.responseXML).find("Group").each(function()
         {
              if(loggedinUserGroup=="")
              {
                  loggedinUserGroup = $(this).attr("Name");
              }
              else
              {
                  loggedinUserGroup = loggedinUserGroup + "\n"+ $(this).attr("Name");
              }
         });
               
  }
 });
}

</script>

Hope this helps... Follow this page for more updates.
Related post- jQuery spservices to get current user name for sharepoint site
Related post- How to display user information using ProfilePropertyLoader in sharepoint

Saturday, February 23, 2013

Set this url as default/Home page of your browser


In this post we are going to set any url as default/Home page of your browser.
Recently one of my friend asked me to do this. So thought of sharing with you guys as well.
Consider we are going to set the http://www.google.co.in as the Default/Home page of the browser.

Add a below anchor tag to your webpage
<A style="CURSOR: hand; font-decoration: underline" href="#" onclick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.google.co.in');">set as your home page</A>

So when user clicks on this button, a popin will appear asking to set google as the home page.
Just click on Ok. That's it, your browser has been updated with the default/Home page as google.com


Hope this helps...


Wednesday, December 5, 2012

Javascript to get query string value by passing the parameters siteUrl and querystringkey



In this post we will be writing a function to retrieve the query string value by passing the parameters siteUrl and querystringkey using Javascript.

Below is the function:
function getQuerystringForUrl(key,siteUrl) {   
    key = decodeURIComponent(key).replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + key + "=([^&#]*)";
    var regex = new RegExp(regexS);           
    var results = regex.exec(siteUrl);
    if (results == null)
        return;
    else
        return decodeURIComponent(results[1]);
}


Hope this helps...

Thursday, February 16, 2012

Javascript/jquery count li elements inside ul

Below is the script with which you can get the count of li present in ul..


Html::

<ul id="myulid">
  <li>List Item1</li>
  <li>List Item2</li>
  <li>List Item3</li>
  <li>List Item4</li>
  <li>List Item5</li>
</ul>

Java Script:: 


<script type="text/javascript">
var myul = document.getElementById('myulid');
var liCount= myul.getElementsByTagName('li').length;
alert(liCount);
</script>


Hope this helps...

Monday, February 6, 2012

How to call code behind server method from a client side javascript

In this post we will see how to call a server side function from JavaScript.
 

HTML::
<div style="visibility: hidden">
<asp:Button ID="mybtn" runat="Server" onclick="mybtn_Click" />
</div>

Java Script::
var hiddenMyBtn = document.getElementById('<%= mybtn.ClientID %>');
hiddenMyBtn.click();

Server side code::
protected void mybtn_Click(object sender, EventArgs e)
{
//Do your stuff
}


Hope this helps...


Popular Posts