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

Tuesday, June 28, 2016

Obtain a list of SharePoint subsites using Javascript CSOM

Here is some code that you can utilize for obtaining a list of SharePoint subsites that the given user has access to:

<div id="selectsubwebs"></div>

<script type="text/javascript">
   var subsites = null;
   var web = null;
   var context = null;
   var subweb = null;
   var renderedHTML = "";
   var scriptbase = "https://rootSiteUrl/_layouts/15/";

   $.getScript(scriptbase + "SP.Runtime.js", function() {
      $.getScript(scriptbase + "SP.js", function() {
         $.getScript(scriptbase + "SP.RequestExecutor.js", getSubWebs);
      });
   });

   function getSubWebs(){
      context = SP.ClientContext.get_current();
      web = context.get_web();
      context.load(web);
      context.executeQueryAsync(onGetWebSuccess, onGetWebFail);
   }

   function onGetWebSuccess(sender, args) {
      //subsites = web.get_webs();  //Complete list of subsites
      subsites = web.getSubwebsForCurrentUser(null);
      context.load(webCollection);
      context.executeQueryAsync(onGetSubwebsSuccess, onGetSubwebsFail);
   }

   function onGetSubwebsSuccess(sender, args) {
      renderedHTML = renderedHTML + "<table id='table_id' class='display'><thead><tr><th>Team Site Title</th></tr></thead><tbody>";
      var webEnumerator = subsites.getEnumerator();
      while (webEnumerator.moveNext()){
         subweb = webEnumerator.get_current();
         renderedHTML = renderedHTML + "<tr><td><a href='" + subweb.get_url() + "' target='_blank'>" + subweb.get_title() + "</a></td></tr>";
      }
      renderedHTML = renderedHTML + "</tbody></table>";

      document.getElementById("selectsubwebs").innerHTML = renderedHTML;

   }
   function onGetSubwebsFail(sender, args){
      alert("Request to retrieve subwebs failed. Error: " + args.get_message())
   }

   function onGetWebFail(sender, args){
      alert("Request to retrieve subwebs failed. Error: " + args.get_message())
   }
</script>

Friday, August 14, 2015

Remove dashed line that appears around elements of an HTML image map

If you discover that you're being plagued by a dashed line that appears around the <area>  elements of your HTML image map whenever a user clicks on a given element of the image map, here is some jQuery code that you can use to remove those dashed lines...

$(document).ready(function() {

     $("area").focus(function() { $(this).blur(); });

}

To help explain matters, the dashed line is simply an indicator that the user placed the focus on the given element when he/she clicked on it.  The above code works by using the blur method to remove the focus from the selected item after it's been has been clicked.

Monday, June 15, 2015

Reading a value from the Web.config file of an ASP .NET Web Application using Javascript

To read a value from the web.config file of an ASP .NET Web Application using javascript, you can do the following:

  1. In your web.config file, add a new <appSettings> with the key and value that you wish for the javascript code to obtain.  In this example, here is the new <appSettings> node, I'm going to reference:

    <appSettings>
         <add key="Environment" value="TEST" />
    </appSettings>


  2. In the HTML code of my default.aspx page, I'm going to add the following javascript function that's going to reference the new <appSettings> node that I just added:

    function getEnvironment() { 
         var environment = '<%= ConfigurationManager.AppSettings["Environment"].ToString() %>';
         alert(environment);
    }
All you have to do is call this function at an appropriate location in your code and it will obtain the value of the respective <appSettings> node.  Naturally, you'll want to swap out the alert call with some valid code, but the idea of this example is to get you rolling.

Thursday, March 20, 2014

Obtain the URL of your root website using Javascript

If you ever need to obtain the URL to your root website via Javascript code (i.e. http://rootWebsite), I've got a couple of good methods for doing so which are presented as follows:

If you're on a SharePoint site want to use CSOM:

var clientContext = new SP.ClientContext();
var rootWebsiteUrl = clientContext.get_site.get_rootWeb();


If you're on a SharePoint site and don't want to use CSOM:

var rootWebsiteUrl = _spPageContextInfo.siteServerRelativeUrl;


If you're not on a SharePoint site or, actually, have no idea what SharePoint is:

var currentLocation = document.location.toString();
var webApplicationNameIndex = currentLocation.indexOf('/', currentLocation.indexOf('://') + 3);
var rootWebsiteUrl = currentLocation.substring(0, webApplicationNameIndex);

Friday, December 6, 2013

How to fix the apostrophe issue in the JQuery AutoComplete control

I recently experienced an issue in which the JQuery AutoComplete control was throwing exceptions when attempting to locate an employee whose last name contained an apostrophe (i.e. O'Brien).  To resolve the issue, I simply added a line of code that replaced the apostrophe character with the proper escape sequence like so:

request.term = request.term.replace("'", "\\'");

Here is the complete function with the new line of code added in the appropriate location:

$("#<%=txtSelectUserName.ClientID %>").autocomplete({
    source: function (request, response) {
        request.term = request.term.replace("'", "\\'");
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/ADGroupManagementWS.asmx/GetAllADUsers",
            data: "{'keywordStartsWith':'" + request.term + "'}",
            dataType: "json",
            async: true,
            success: function (data) {
                response(data.d);
            },
            error: function (result) {
                alert("Due to unexpected errors, data could not be loaded");
            }
        });
    },
    minLength: 1
});

Tuesday, October 8, 2013

How to define the CSS class that should be used during an onMouseOver or onMouseOut event for a web control

In case you would ever like to leverage an existing CSS class for your web control whenever an mouse event is triggered (i.e. onMouseOver or onMouseOut), here is a quick example of how to do that:

<input type="button" class="ui-state-default ui-widget-content" onMouseOver="this.className='ui-state-default ui-widget-content ui-state-hover'" onMouseOut="this.className='ui-state-default ui-widget-content'" value="Submit" id="btnSubmit" onClick="SubmitForm();" />

NOTE: In the above example, I'm leveraging the CSS classes that are already defined for a jQuery UI Calendar control that exists on another part of the page.  By leveraging those CSS classes for my control, I can keep the look and feel of all controls on the page as consistent as possible.

Also, there may come a time when you need to assign the CSS classes a web control uses via Javascript code. In the following example, I'm using a Javascript function to specify the CSS classes that will be programmatically defined for the given control based on the isSelected value (i.e. whether or not the control has been selected):

function SetButtonStyle(controlId, isSelected) {
     if (isSelected) {
          document.getElementById(controlId).onmouseout = "this.className='ui-state-default ui-state-highlight ui-state-active'";
          document.getElementById(controlId).onmouseover = "this.className='ui-state-default ui-state-highlight ui-state-active'";
          document.getElementById(controlId).className = "ui-state-default ui-state-highlight ui-state-active";
      }
      else {
          document.getElementById(controlId).onmouseout = "this.className='ui-state-default ui-widget-content'";
          document.getElementById(controlId).onmouseover = "this.className='ui-state-default ui-widget-content ui-state-hover'";
          document.getElementById(controlId).className = "ui-state-default ui-widget-content";
      }
}

Tuesday, August 6, 2013

Calculating the number of days since an event took place using Javascript

If you're looking for a way to determine how many days have passed since a given event took place using Javascript, here is a function that will provide you with the basic functionality that you're looking for:

function calculateDaysSinceEvent(eventDateTime) {
    // Obtain the current date and time
    var todaysDateTime = new Date();
    // Calculate the difference in time between today and when the event took place
    var diff = todaysDateTime - eventDateTime;
    // Convert the difference to a value that represents a day and round the value up
    return Math.round(diff/(1000*60*60*24));
}

Wednesday, July 31, 2013

Javascript function for converting a datetime object to a specific format

Chances are very good that at some point during your journey with SharePoint 2013 you're going to need a javascript function that you can use for converting a datetime object into a nice, user-friendly output string for display purposes.  In the code sample I'm about to provide, the javascript function will return an output string that matches the following format:

Wednesday, 7/13/2013

Here's the basic function that will give you the output presented above:

function getDateString(dateTime) {
 var weekday=new Array();
 weekday[0]="Sunday";
 weekday[1]="Monday";
 weekday[2]="Tuesday";
 weekday[3]="Wednesday";
 weekday[4]="Thursday";
 weekday[5]="Friday";
 weekday[6]="Saturday";

 var dayOfWeek = weekday[dateTime.getDay()];
 var month = dateTime.getMonth() + 1;
 var day = dateTime.getDate();
 var year = dateTime.getFullYear();

 return dayOfWeek + ', ' + month + '/' + day + '/' + year;
}


Thursday, November 1, 2012

Programmatically creating a custom hyperlink within a content editor web part

Not certain how useful this is; however, I was recently asked if I could update the title of a web part hosting a view to a SharePoint list so that it would not only be larger, but would also incorporate the upcoming date of the next weekly meeting in the title's text.  The solution I decided to implement for this particular site consisted of the following activities:
  1. Set the Appearance -> Chrome Type of the list web part to "None" in order to hide the existing title of the list web part
  2. Added a new Content Editor Web Part immediately above the applicable list web part
  3. Used Notepad to create a javascript file, OutstandingRCATitle.txt, that would create the custom hyperlink within the content editor web part
  4. Uploaded the custom javascript file to the Site Assets library of the given SharePoint site
  5. Linked the content editor web part to this file via the Content Link parameter of the content editor web part
With that accomplished, I simply had to add the appropriate javascript code to the OutstandingRCATitle.txt file in the Site Assets library to provide the requested functionality.  This functionality is listed as follows:
  1. Increase the size of the link to make it stand out to the users (i.e. used <h1> for this purpose)
  2. Append the date of the next weekly team meeting to the link (i.e. the meeting always takes place on a Tuesday so I created code that would add additional days to the current date so that the upcoming Tuesday's date would be listed)
  3. Have the link reference the appropriate view to the list (i.e. I maintained the link to the original AllItems.aspx view of the list; however, you could specify another view)
Here is the javascript code that I used for meeting this particular user's needs:
<script language="javascript"> var now = new Date(); var todaysDay = new Date().getDay(); var nextTuesdaysDate = new Date(); var numDays; switch (todaysDay) { case 0 : numDays = 2; break; case 1 : numDays = 1; break; case 2 : numDays = 0; break; case 3 : numDays = 6; break; case 4 : numDays = 5; break; case 5 : numDays = 4; break; case 6 : numDays = 3; break; } nextTuesdaysDate.setDate(now.getDate() + numDays); var displayDate = "<h1><a href='../Lists/Outage/AllItems.aspx' class='customLink'>Outstanding RCAs to be reviewed on " + nextTuesdaysDate.toLocaleDateString() +"</a></h1>"; document.write(displayDate); </script>
Since this was a one-time request for a particular user (i.e. a priority one at that) and not something that would be applicable to multiple sites, I decided to use this solution; however, I would have used a radically different approach to solving this problem if this was something that was required across multiple sites.  Not certain how useful this might be to others, but I thought I'd share anyway.

Thursday, September 27, 2012

Strategies for implementing a 'Wait Notification' for a long running operation: standard ASP .NET

If you're looking for a good way to inform the users of your ASP .NET web application that processing is actually taking place during a long running process, here is a simple strategy you can use that involves standard ASP .NET.  Now, in order to make this work, you'll need to make three changes to the web page hosting the process which are listed as follows:
  1. Add a <div> tag to your HTML code that will be used for hosting the "Processing..." message or image.  Here is a simple example:

    <div align="center" id="div_ProcessingMessage" runat="server" style="display: none;"><span> Processing... </span></div>

  2. Add a javascript function that displays the above-mentioned <div> when called (NOTE: you could also add code to disable controls that you don't want the user touching in the event of a long running process).  Here is a simple example:

    <script type="text/javascript">
    function EnableProcessingMessage() {
        var test = document.getElementById('div_ProcessingMessage');
        test.style.display = "";
    }
    

  3. Add an "onsubmit" attribute to the <form> tag of your web page that calls the above-mentioned javascript function.  Here is a simple example:

    <form id="form1" runat="server" onsubmit="EnableProcessingMessage()">
After these changes are in place, you can fire up your application and the message or image contained in the <div> tag will pop up in the specified location whenever a postback is triggered on the page.  The longer the process takes, the longer this message will stay visible to the users.  Once the postback operation is complete, the message will be hidden again.

By the way, if you don't want the users clicking on various controls during a long running operation, you can prevent them from doing so by adding code to your javascript method that can temporarily hide or disable those controls.

Now, if you're using AJAX, this strategy won't work so I'll provide you with another solution for that in my next post...

Monday, June 18, 2012

Javascript code that can verify if special characters are used in a textbox

In the event that you would like to use client-side code to (1) inform a user that he/she has entered invalid characters in a textbox control, (2) highlight that control, and (3) place the focus on it, the following Javascript code can be added to a validation function to carry out all of three of those actions:

function ValidateRequest() { ... if (form.userinput_textbox.value != 0)
{ var userInputField = form.userinput_textbox.value; var invalidChars = "/!@#$%^&*(){}[]<>\\"; for (var i = 0; i < userInputField.length; i++) { if (invalidChars.indexOf(userInputField.charAt(i)) != -1) { window.scrollTo(0, 0); alert ("Please don't use any special characters or punctuation within the given textbox control."); form.userinput_textbox.backgroundColor = "C6ECFF"; form.userinput_textbox.focus(); return false; } } } ... }

Friday, April 13, 2012

Programmatically initiate javascript from code behind

Occassionally, situations may arise in which you want to initiate javascript from the C# code behind of your web application.  In the following simple example, the code in the Page Load event is triggering a simple alert message to fire; however, the sky is the limit with all the possibilities that this opens up:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (!ClientScript.IsStartupScriptRegistered(this.GetType(),"alert"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('All leases must be re-assigned to another parent before the delete operation may continue.  You may use this view to re-assign those leases.');", true);
        }
    }
}

Enjoy!