Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Saturday, February 7, 2015

Add custom script to Nintex forms

Share/Save/Bookmark

At the end of this blog post you will learn how to

- Submit data to mulitple lists from a single form(here Nintex)
- Create a new item using client side script(Jquery)
- Have your own code/javascript run when submitting the OOTB submit/save button
- Add custom script or jquery in Nintex forms accessing controls



NWF$(document).ready(function () {

var formclick = $("input[commandtype*='Save']").attr("onclick");
formclick = "if(!UpdateContacts()){return false;};" + formclick.replace("javascript:","");
$("input[commandtype*='Save']").attr("onclick",formclick);

});

Above function will bind custom script/function to the OOB save/submit button on the Nintex form but for some reason i could not get the client validation happen before the submit works.

function UpdateContacts()
{

 mode = "New";
 var aname = $('#'+accountnameCtrl).val();
 var fn = $('#'+firstnameCtrl).val();
 var ln = $('#'+lastnameCtrl).val();
 var email = $('#'+emailCtrl).val();
 var phone = $('#'+phoneCtrl).val();

  $().SPServices({
        operation: "UpdateListItems",
        async: false,
        batchCmd: "New",
        listName: "Contacts",
        valuepairs: [["FirstName", fn],["LastName", ln],["Phone",phone],["Email",email]],
        completefunc: function(xData, Status) {
        console.log(status);

    $(xData.responseXML).find("ErrorText").each(function() {
     alert("Error :"+$(this).text());
    });
    }

});

}


Subscribe

Thursday, June 12, 2014

Check in file using Client script


Share/Save/Bookmark

Here is a simple way of doing few file operations in sharepoint using client script. You can try JQuery for client object model or CSOM or JQuery with SPServices(in my case).

function DiscardCheckOut(url)
{

    var errorMessage = "";

    $().SPServices({
    operation: "UndoCheckOut",
    async: false,
    pageUrl: url,
    completefunc: function (xData, Status) {
         $(xData.responseXML).find("errorstring").each(function() {
         errorMessage = $(this).text();
         });

        $(xData.responseXML).find("faultstring").each(function() {
               errorMessage += $(this).text();
         });

        var undoCheckOutVal= $(xData.responseXML).find("UndoCheckOutResult").text();
        if(undoCheckOutVal == "true")
             alert("Operation success");
        else
            alert("Operation failed:"+errorMessage);
     }
});

}

function CheckIn(furl)
{

   var errorMessage = "";

   $().SPServices({
   operation: "CheckInFile",
   async: false,
   pageUrl: furl,
   comment': "Checked in from checkout list",
   CheckinType: 1,
   completefunc: function (xData, Status) {
       //get errorstring
        $(xData.responseXML).find("errorstring").each(function() {
             message = $(this).text();
        });

       //get fault string
       $(xData.responseXML).find("faultstring").each(function() {
            message +=" "+ $(this).text();
       });

      var checkInResultVal= $(xData.responseXML).find("CheckInFileResult").text();
      if(checkInResultVal == "true")
            alert("Check-in operation success");
      else
            alert("Operation failed:"+errorMessage);
   }
   });
}



Subscribe

Tuesday, May 27, 2014

Execute script after MDS load

Share/Save/Bookmark

$(document).ready() always works when its a complete page load/refresh but not when there are controls enabled with ajax doing async callback or Minimial download strategy(sharepoint 2013) is enabled for the site that reloads only the changes in the page.Know more about Minimal Download Strategy by reading this.

Also, Its not always necessary that the page is loaded following MDS but sometime may reload. So both cases need to be handled when writing scripts(jquery/javascript)
Below is the code that i could make use of that could fulfill this scenario.

$(function () {
      ExecuteOrDelayUntilScriptLoaded(function () {
      if (typeof asyncDeltaManager != "undefined")
            asyncDeltaManager.add_endRequest(doSomething); //after MDS loads the changes
      else doSomething();
      }, "start.js");
});

function doSomething()
{
   //write something
}

 Subscribe

Friday, May 23, 2014

Autocomplete using SPServices with JQuery

Share/Save/Bookmark

Call it auto suggestion or type ahead or auto complete, its pretty similar that im trying to achieve here in SharePoint using SPServices API with JQuery.
Get your copy of SPServices js from http://spservices.codeplex.com/ and have it in a library or layouts folder so it can be referenced in the script that we gonna write.

Here, im implementing a sharepoint site page that has a custom filter option that will allow user to filter the data in mulitple listviewwebpart added to the same page.Sometime names may sound same but spell different, so i want to give auto suggestions when user starts typing the text in filter textbox.

$(document).ready(function(){
 $().SPServices.SPAutocomplete({
     sourceList:"Employee list",
     sourceColumn: "FullName", // SPField name from which data will be pulled using lists webservice
     columnName:"FilterByName", // either sp field name if using on list form or input field control title attribute
     ignoreCase:true,
     numChars:3, //autocomplete shows when there is a minimum of 3 char in the textbox of the field/control
     slideDownSpeed: 1000,
  });
});

Once value is set in filtertexbox  and submitted i have an additional script that appends the querystring FilterField1=fileldname&FilterValue1=value that will filters the data in multiple list webparts.

SPServices made developers job easy when it comes to writing client side code. Ofcourse, you can achieve the same thing by writing your own code from scratch with a jquery ajax request to sharepoint lists webservice and bind results with textbox.
Im hoping SPServices will introduce a way to find the input control not just by 'Title' but also by name/id because some sharepoint input controls(may not be list forms) will not have title attribute set.


Subscribe

Saturday, January 19, 2013

Set width of div part of iframe

Share/Save/Bookmark

How to set the width(in percentage) of the element that is part of iframe?
my first attempt :
$(document).ready(function()
{
$("#divid").css("width","50%");
});
Above script did not work as the script gets triggered immediately after document
loads but before iframe renders
So i tried the below, which did not work for me(in IE 8)
$('iframe').ready()
finally i could run the script on load of iframe with below code
though it failed to set the width property as it was not able to find the div
$('iframe').load(function()
{
   $("#divid").css("width","50%");
}

To access the contents of the iframe use
$("iframe").contents().find("#divid")
Geat!! it could get the div element but could not set the css property as i
was trying to override the css property that already has important tag set
So, how do i set my css property as important through jquery?
Here you go...
$("iframe").load(function () {
        $("iframe").contents().find("#divid").attr("style", "width:50%!important");
    });

voila!!So much learnt today :)


 Subscribe

Sunday, May 6, 2012

Read SharePoint Service using JQuery

Share/Save/Bookmark


I had spent a day to know that soap response can be read at the event complete but not success.
In success event soapresponse(data.responseXML) is always empty. I'm not sure if its a sepcial case with soap.

Below function of Jquery retrieves the SocialTag count of a specific URL from all users.
Complete event triggers all the time after the service call resulting in success or error. So i used a flag based on which i can get to know if the service call is success or error.

function GetLikeCountFromService(domId, url) {

var tagName = "I like it";
var queryStatus = true;


var soapEnv =
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>\
<soap:Body> \
<GetTagTermsOnUrl xmlns='http://microsoft.com/webservices/SharePointPortalServer/SocialDataService'>\
<url>" + url + "</url>\
<maximumItemsToReturn>'100</maximumItemsToReturn> \
</GetTagTermsOnUrl> \
</soap:Body> \
</soap:Envelope>";

$.ajax({
url: '/_vti_bin/socialdataservice.asmx',
type: 'POST',
dataType: "xml",
data: soapEnv,
complete: function (data) {

//process only if the query is success
if (queryStatus) {
var likeCount = 0;
$(data.responseXML).find("SocialTermDetail").each(function () {
var term = $(this).find("Term").find("Name").text();
//alert($(this).find("Term").find("Name").text());
if (term == tagName) {
likeCount = $(this).find("Count").text();
// set the like count
$(domId).text(likeCount);
return;
}
});
,

error: function (all, textStatus, errorThrown) { queryStatus = false; alert(errorThrown); },
contentType: "text/xml; charset=\"utf-8\""
});
}



JQuery made life easy with flexible API. I have implemented another function similar to it that will like a URL, in sharepoint terms tagging a url with "I Like It". As a combination this will work as similar to the Social Like feature in Facebook.

Subscribe