Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, October 15, 2015

Get Web Part Title and Add Link / Text / Image to the right side of the web part title

Here is the code to get web part title and then add image or text or link in web part title and right align that.

You have to put this code in Script editor web part or put this code in a file & store somewhere & provide link to master page or provide link to content editor web part


// Function to add link/text/icon in right side of the web part title

 $(document).ready(function () {

    var className='.ms-webpart-titleText';

    $(".ms-webpart-chrome-title span h2").each(function(inx){       
        var webPartTitle = $(this).text();
               
        //Check web part title
        if(webPartTitle.indexOf("My Web Part Title")>=0)
        {
            var openUrl ="javascript:OpenPopUpPageWithTitle(\""+_spPageContextInfo.siteServerRelativeUrl+"/Style Library/MyFolder/MyPage.aspx?IsDlg=1\", RefreshPage, null, null, \"My Page Title\"); return false;";
           
            $(this).prepend("<div class='small' title='Click to open my page' style='cursor: pointer; display: inline-block;  float:right; text-align:center'><span id='spanMore' title='My Page' class='glyphicon glyphicon-th-list' aria-hidden='true' onclick='"+openUrl+"'>*****</span>&nbsp;</div>") ;
        }
    });
});

Enjoy Codding in SharePoint

Thursday, September 19, 2013

Download ebook Professional JavaScript for Web Developers, 3rd Edition

Download ebook Professional JavaScript for Web Developers, 3rd Edition


Book Description

If you want to achieve JavaScript's full potential, it is critical to understand its nature, history, and limitations. To that end, this updated version of the bestseller by veteran author and JavaScript guru Nicholas C. Zakas covers JavaScript from its very beginning to the present-day incarnations including the DOM, Ajax, and HTML5. Zakas shows you how to extend this powerful language to meet specific needs and create dynamic user interfaces for the web that blur the line between desktop and internet. By the end of the book, you'll have a strong understanding of the significant advances in web development as they relate to JavaScript so that you can apply them to your next website.

Book Details

Publisher:Wrox
By:Nicholas C. Zakas
ISBN:978-1-1180-2669-4
Year:
Pages:960
Language:English
File size:53.1 MB
File format:PDF

Download ebook Professional JavaScript for Web Developers, 3rd Edition

Thursday, September 6, 2012

How to calculate difference between two dates in javascript/jquery


Simple steps to calculate difference between two date fields using JavaScript/JQuery 
In some scenario, we need to calculate the difference between two dates from the client side. Here we are going to demonstrate all about date fields using javascript such as Javascript date field validation for different format, difference between two dates in days, hours, minutes, seconds, years and weeks
Very strong and simple Javascript validation for date fields for format dd/mm/yyyy 
Following javascript function simply verify and return result for checking valid date from client side itself. It will automatically validate leap year entries and return correct result. That means if we pass ’29/02/2011′ to the function it will be return false. If we are passing ’29/02/2012′ to the function it will return true. So we don’t need to bother about the leap year or other complex things.
function isValidDate(dateStr) {
// Date validation Function
// Checks For the following valid Date formats:
// DD/MM/YYYY
var re = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\
d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))
|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]
\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
var valid = re.test(dateStr);
if (valid == false) {
alert(dateStr + ' Date is not in a valid format.')
return false;
}
return true;
}
How to calculate the date difference from client side using javascript?
Now we are going to find the difference between two date fields from the client side javascript or jquery. In some of the scenario, we need to find the number of days between two selected dates  like leave applying modules, hotel room booking etc. In this case we can simply calculate the difference between from date and to date using following function in javascript.
Here we are having two date fields for from date and todate. User has to select a from date and to date by using this controls. Todate should be greater than from date. When user select from date or todate we will call javascript function calculate()  and this function finds the difference between two dates and display the difference in the label. Its also validate as todate should be greater than the from date.
function calculate() {
var value1 = document.getElementById('<%=txtDateFrom.ClientID%>')
.value.split("/");
var value2 = document.getElementById('<%=txtDateTo.ClientID%>')
.value.split("/");
if (value1 != "" && value2 != "") {
var day1 = parseFloat(value1[0]);
var month1 = parseFloat(value1[1]);
var year1 = parseFloat(value1[2]);
var day2 = parseFloat(value2[0]);
var month2 = parseFloat(value2[1]);
var year2 = parseFloat(value2[2]);

if ((year2 < year1) || (year2 == year1 && month2 < month1) || 
(year2 == year1 && month2 == month1 && day2 < day1)) {
alert('From Date should greater than Date From');
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML = "0";
return;
}                    
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
var fromDate = new Date(year1, month1 - 1, day1);
var toDate = new Date(year2, month2 - 1, day2);
// Convert both dates to milliseconds
var dateFrom = fromDate.getTime();
var dateTo = toDate.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(dateTo - dateFrom)
// Convert back to days and return
var DiffDays = Math.round(difference_ms / ONE_DAY)
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML 
= parseFloat(DiffDays) + 1;
}
}
In order to call this javascript function on aspx textbox change event, we need to set attributes to the textbox on code behind as follows.
protected void Page_Load(object sender, EventArgs e)
{
    txtFromDate.Attributes.Add("Onchange", "calculate();");
    txtToDate.Attributes.Add("Onchange", "calculate();");
}
ASPX page having two date fields as follows :
<table>
 <tr>
 <td>
 First Date:
 <asp:TextBox runat="server" ID="txtFromDate" />
 (DD/MM/YYYY format)<br />
 Second Date: Date:
 <asp:TextBox runat="server" ID="txtToDate" />
 (DD/MM/YYYY format)<br />
 <center>
 <asp:Button runat="server" ID="btnCheck" Text="Check" 
 OnClientClick="return calculate();" />
 </center>
 </td>
 </tr>
</table>




Reference :

How to calculate difference between two dates in javascript/jquery

Wednesday, September 5, 2012

Disable Right click of mouse


How to disable right click functionality from the asp.net web page
In some of the web page has the requirement to protect source code from the users. Users can right click the page and take the source code. In order protect right click functionality on the web page we can implement javascript functionality to prevent user’s right click on the web page. So user not able to access features available on the right click menus.
By implementing javascript method we can identify the right click event from the user by checking the button code and prevent if the user clicks right click. Below mentioned web page prevented to click right click by the user. When the user trying to right click it will return warning message to user and return the action.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DisableRightClick.aspx.cs"
 Inherits="ExperimentLab.DisableRightClick" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Sample to Disable Right Click of Page</title>
 <script language="JavaScript" type="text/javascript">
 //Message to display whenever right click on website
 var message = "Sorry, Right Click have been disabled.";
 function click(e) {
 if (document.all) {
 if (event.button == 2 || event.button == 3) {
 alert(message);
 return false;
 }
 }
else {
 if (e.button == 2 || e.button == 3) {
 e.preventDefault();
 e.stopPropagation();
 alert(message);
 return false;
 }
 }
 }
if (document.all) {
 document.onmousedown = click;
 }
else {
 document.onclick = click;
 }
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 In this page right click not allowed.
 </div>
 </form>
</body>
</html>
Reference from : http://tuvianblog.com/2012/03/20/disable-right-click-on-a-web-page-in-asp-netc-using-jqueryjavascript/

Tuesday, June 14, 2011

How to enable/disable buttons in ribbon conditionally?

In this article I will cover how we can enable and disable the controls from ribbon based on any specific column value. For an instance I have a list column "State", if selected row is having status "active" then and then button should be enable in Ribbon, otherwise ribbon button should remain disable.

For how to write Ribbon declaration please refer my previous articles.


In above image you can see we have one button "New" in ribbon within group "Console". Please refer the source code for Ribbon's declaration. We are going to use delegate control for injecting ECMA script on fly for desired list.
Below are the events causes ribbons to refresh so button can be turned enable/disable.
  • Checkbox from every row
  • SelectAll/DeselectAll checkbox from header row
  • On every row select
On each of above events after executing their respective functionality they instruct the ribbon to refresh. On received of refresh event ribbon calls Enable script for each of its control. Enable Script is the attribute which points to JavaScript function which can contain the logic for deciding button to be enabled or disable. You can mention the JavaScript function name to Enable Script attribute while declaring the Ribbon XML element.
Now let's see how sample is going to work.
  • On page loads and when no row is selected button will be disable
  • When user clicks checkbox of row and that row is having "Active" as status value then button will get enable
  • When user clicks row and that row is having "Active" as status value then button will get enable
  • If row is selected and button is enable and user click select all checkbox then ribbon will get refresh and button will be disable
So to achieve required functionality what we need is,
  • A function which will return a Boolean flag for ribbon to enable/disable button
  • We need to attach our own events on row click, row checkbox click and header checkbox click
  • So in our own functions we will retrieve the row and it's all cell values
  • Based on status cell value we will set the global flag true/false.
  • Then we will call Ribbon refresh, which eventually will enable/disable the button
Let's see how we can attach our own functions to various click events,


var _isButtonEnable = false;
var statusIndex = 2;
var row;

_spBodyOnLoadFunctionNames.push("registerEvents");

function isButtonEnablefn() {
    if (_isButtonEnable != 'undefined')
    { return _isButtonEnable } else
        return false;
}

function registerEvents() {
    var ctxCur = GetCurrentCtx();
    var SPGridViewGuid = ctxCur.listName;
    var oTables = document.getElementsByTagName("TABLE");
    for (var i = 0; i < oTables.length; i++) {
        if (oTables[i].id != "") {
            var listGUID = oTables[i].id.split("-{");
            if (listGUID[0] == SPGridViewGuid) {
                var oRows = oTables[i].getElementsByTagName("TR");

                var chkbxs = oRows[0].getElementsByTagName('input');
                if (chkbxs != null) {
                    chkbxs[0].attachEvent('onclick', selectAllClicked);
                }

                for (var j = 0; j < oRows.length; j++) {
                    if (j != 0) {
                        oRows[j].attachEvent('onclick', rowClicked);
                        var chkbx = oRows[j].getElementsByTagName('input');
                        if (chkbx != null) {
                            chkbx[0].attachEvent('onclick', rowCbxClicked);
                        }
                    }
                }
            }
        }
    }
}

function selectAllClicked() {
    _isButtonEnable = false;
    RefreshCommandUI();
}

function rowClicked() {
    setSelectedItem();
}

function rowCbxClicked() {
    setSelectedItem();
}

function setSelectedItem() {
    var evt = null;
    //capture the curren event
    evt = window.event;
    //retrieve the source of event
    var o = GetEventSrcElement(evt);
    //if source element is ECB menu or link then return don't do anything
    if (o != null && ElementContainsLink(o))
        return;
    // Close ECB menu if it is already open   
    if (clearECBMenu(o)) {
        CancelEvent(evt);
        return false;
    }
    //Retrieve the Row from which the event has raised
    var tr = GetItemRow(evt);
    var ctxCur = CtxFromRow(tr);

    if (CountSelectedItems(ctxCur) == 1) {
        var items = GetSelectedItemsDict(ctx);
        var k
        for (k in items) {
            var itm = items[k];
            //alert('List GUID :' + ctxCur.listName + '-- Item ID:' + itm.id);
            // Keep selected row in backstore we will need this later on in ribbon events
            var curRow = saveCurrentRow(tr, itm.id);
            // If Row Item Status is Active then turn on New Button.
            (curRow.cells[statusIndex].outerText == SP.MyResource.Active) ? _isButtonEnable = true : _isButtonEnable = false;
        }
    }
    else { _isButtonEnable = false; }
    RefreshCommandUI();
}

function saveCurrentRow(tr, curSelectedItemId) {
    var tab = tr;
    while (tab.tagName != "TABLE")
        tab = tab.parentNode;
    var rows = tab.rows;
    var i = 0;
    //This loop will fix the index for Phase State
    for (i = 0; i < tab.cells.length; i++) {
        if (tab.cells[i].outerText.trim() == SP.MyResource.State.trim()) {
            statusIndex = i;
            break;
        }
    }
    var iid;
    var rgiid;
    //This loop will fix the current selected row
    for (i = 1; i <= rows.length; i++) {
        iid = rows[i].getAttribute("iid");
        rgiid = iid.split(",");
        if (rgiid[1] == curSelectedItemId) {
            if (typeof (row) == "undefined") row = [];
            row[curSelectedItemId.id] = rows[i];
            return rows[i];
        }
    }
    return null;
}

function NewButtonClick() {
    var url;
    var ctxCur = GetCurrentCtx();
    if (CountSelectedItems(ctxCur) == 1) {
        var items = GetSelectedItemsDict(ctx);
        var item
        for (item in items) {
            var itm = items[item];
            alert('List GUID :' + ctxCur.listName + '-- Item ID:' + itm.id);
        }
    }
}

// javaScript String object's extension method for trim operation
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

Wednesday, April 13, 2011

Opening a SharePoint 2010 dialog box for list form

If you want to open a window in a dialog from clicking a link then simply use the following JavaScript as the href property.



javascript:var options = {url: '/Lists/MyList/NewForm.aspx?IsDlg=1&ContentTypeId=0x001989BCF16D8914CAF8862B0C6C89E091E', title: 'Showing List'}; void(SP.UI.ModalDialog.showModalDialog(options))

As you can see this is simply taking the script you would usually call and adapting it to work in the href of a hyperlink anchor. It needs to be all on one line and return void when called.
So why might you want to do this? Many reasons. Perhaps you have a list with multiple content types and you wish to open the new item form in a dialog AND change the title from the default “[List Title] – New Item” depending on which content type the item is being created from. The snippet above illustrates this. Or perhaps you wish to open a document library in a dialog. Or even an external site.

Also you can use following script in your code :


public string GetDialogURL(string url, bool refreshOnClose , double width, double height )
        {
            string strDialogURL = "javascript:function demoCallback(dialogResult, returnValue){ SP.UI.Notify.addNotification('Operation Successful!'); SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);  }function(){setTimeout('editEffect()', 200)}editEffect(); function editEffect(){" +
                                  " var options = { url:'" + url + "'," +
                                  "tite: 'Move Documents',allowMaximize: true ,showClose: true,width:" + width + ",height:" + height;


            if (refreshOnClose)
            {
                strDialogURL += ",dialogReturnValueCallback: demoCallback";
            }
            strDialogURL += "};SP.UI.ModalDialog.showModalDialog(options);}";
            return strDialogURL;
        }


Check this also :

SharePoint: Opening a 2010 Dialog Box from Quick Launch

How to get current logged user information using JavaScript ?

This is post which is simple and not really needed. But when I started writing the code in ECMAScript I have faced problems in getting the logged in user information. So, my readers may feel good after see this post and really most the users are looking for this too.
By this time, we have really understood all about ECMAScript Client Object Model and debugging. So, it's easy for us to know it well.
Please find the code below to get the current user information.



<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">

Now copy & paste this JavaScript code after above mentioned tag :

<script type="text/ecmascript">

        ExecuteOrDelayUntilScriptLoaded(getUserData, "sp.js"); 

       
    // To Get Current User Name
    var context = null; 
    var web = null; 
    var currentUser = null; 
    var currentUserId=''
    function getUserData() {

            context = new SP.ClientContext.get_current(); 
        web = context.get_web(); 
        currentUser = web.get_currentUser(); 
        currentUser.retrieve(); 
        context.load(web);
        context.executeQueryAsync(onSuccessMethod, onFaiureMethodl);
       
    } 
       
    function onSuccessMethod(sender, args) { 
        var userObject = web.get_currentUser(); 
        alert('User name:' + userObject.get_title() + '\n Login Name:' + userObject.get_loginName()); 

    }
   
    function onFaiureMethodl(sender, args) {
        alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace()); 
    }
    //--- END Get Current User Name

</script>


Friday, April 8, 2011

Set default value for People Picker via JavaScript

First open entry form (NewForm.aspx / EditForm.aspx / DispForm.aspx) in advanced mode in sharepoint designer. Then search for tag :


<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">


Now copy & paste this JavaScript code after this tag :


<script type="text/ecmascript">
 //Function search for people picker by its no and set default value string type
 //If we have 2 people picker in entry form & we want to set value to 2nd no. then "pickerNo=2"
 function fillPeoplePickerWithCurrentUser(pickerNo,userLoginName )
   {
      if(userLoginName != null)
      {
         var pp = getPickerImputElement(pickerNo);
  
         if(pp != null)
         {
           pp.innerHTML = userLoginName;
         }
      }
   }

  function getPickerImputElement(pickerNo)
  {
    var result = '';
    var divs = document.getElementsByTagName('DIV');
    var j = 0;

     for(var i=0; i < divs.length; i++)
     {
        if(divs[i ].id.indexOf('UserField_upLevelDiv') > 0)
        {
           j++;
           if(j == pickerNo)
           {
            result = divs[i ];
            break;
           }
        }
     }
     return result;
  }
</script>

Sunday, February 13, 2011

Useful JavaScript global variables in SharePoint

If you’re using custom JavaScripts with SharePoint 2010 some global JavaScript variables may come in handy.
These variables work if you’re using SharePoint’s default or any other custom master page. 

L_Menu_BaseUrl – the base URL of the site / subsite. Very useful when you need to determine the absolute path of the site in JavaScript. Example: document.location = L_Menu_BaseUrl + ‘lists/calendar/allitems.aspx’ //redirects to Calendar list 

L_Menu_LCID – the LCID of the site you’re in. Useful if you need to determine the language of the site. The list of Locale IDs can be found here. 

_spUserId – the ID of the logged in user.

SharePoint Framework Web Part Properties

Hi, I have created examples for SharePoint Framework Web Part Property Field examples. Here I have covered almost all the properties &...