JavaScript / jQuery: Hide/show fields

With SharePoint we use a lot of lists and libraries to store and share information, we add and change this information with the help of forms. In most cases we create one form with all the information required for the content. Even if not all the information is required for all types of content or if it depends on a phase or status. With the help of jQuery and JavaScript we can create a more dynamic form that will hide/show fields based on selected values of fields. Make sure to disable the quick option, otherwise user will be able to edit the field outside of the provided solution.

SharePoint 2013/Online: Disable Quick edit

  1. Open the list or library settings
  2. Open the Advanced settings
  3. Set Quick Edit to No

SharePoint 2010: Disable Datasheet editing

  1. Open the list or library settings
  2. Open the Advanced settings
  3. Set Datasheet to No

JavaScript: New Form

  1. Open your favorite JavaScript Editor.
  2. Create a new JavaScript file called NewFormHideShow.js
  3. Add the following base code to the JavaScript file.

    $( document ).ready(function() {
       
    }
    );
  4. The first step is to hide the columns. Find the display names of the field that need to be hidden. Note that you need the name located in the HTML nobr tag.
  5. You can use a DOM explorer to find the correct names.
  6. For each field add the following code.
    $('nobr:contains("[Field Name]")').closest('tr').hide(); 
    
  7. In my example I hide two fields, Finalized Date and Finalized By. My example code for the document ready function is shown below.
    $(document).ready(function()
       {
          $('nobr:contains("Finalized Date")').closest('tr').hide(); 
          $('nobr:contains("Finalized By")').closest('tr').hide();
       });
    
  8. The second step is to make the function that hides or shows the fields depended on the selected value.
  9. Add the following code to the JavaScript.
    (function($){
       function showHideRegionLocation() 
       {
          var FeedbackMatchingValue = 'Final';
    
          var thisDiv = $("select[title='Status']"); 
          var mmFieldValue = thisDiv.find("option:selected").text();
    		
          $('nobr:contains("Finalized Date")').closest('tr').hide(); 
          $('nobr:contains("Finalized By")').closest('tr').hide();
    			
          if (mmFieldValue.indexOf(FeedbackMatchingValue) > -1) 
          {
             $('nobr:contains("Finalized Date")').closest('tr').show(); 
             $('nobr:contains("Finalized By")').closest('tr').show();
          } 					
       }
    
  10. Set the var FeedbackMatchingValue to the value which will show the hidden fields.
  11. Set the var thisDiv to the name of the Field that is used to show/hide the fields. Note that different types are just for different columns example Select or Input.
  12. Add the hide and Show codes. The code hides or show the table row (tr).
  13. Add the final function to the code. This part makes sure the functions runs when a users selects and/or reselects the option.
    $(document).ready(function() {
       $("select[id^='Status'").on('blur', showHideRegionLocation).on('change', showHideRegionLocation);
       });
    })(window.jQuery);
  14. Change the value after id^ to the field that contains the value on which field are being shown/hidden.
  15. The final code looks like this.
    $(document).ready(function()
       {
          $('nobr:contains("Finalized Date")').closest('tr').hide(); 
          $('nobr:contains("Finalized By")').closest('tr').hide();
    });
    
    (function($){
       function showHideRegionLocation() 
       {
       var FeedbackMatchingValue = 'Final';
       
       var thisDiv = $("select[title='Status']"); 
       var mmFieldValue = thisDiv.find("option:selected").text();
    		
       $('nobr:contains("Finalized Date")').closest('tr').hide(); 
       $('nobr:contains("Finalized By")').closest('tr').hide();
    			
       if (mmFieldValue.indexOf(FeedbackMatchingValue) > -1) 
       {
          $('nobr:contains("Finalized Date")').closest('tr').show(); 
          $('nobr:contains("Finalized By")').closest('tr').show();
       } 	
    }
    
    $(document).ready(function() {
       $("select[id^='Status'").on('blur', showHideRegionLocation).on('change', showHideRegionLocation);
       });	
    })(window.jQuery);
    

JavaScript: Edit Form

  1. The edit form is almost completely the same, only the last function is different.
  2. Open your favorite JavaScript Editor.
  3. Create a new JavaScript file called EditFormHideShow.js
  4. Follow the steps 3 – 12 from the chapter JavaScript: New Form.
  5. Add the final function to the code. This part makes sure the functions runs when a users selects and/or reselects the option.
    $(document).ready(function() {
       setTimeout(function() {
          showHideRegionLocation();
       }, 1000);
       $("select[id^='Status'").on('blur', showHideRegionLocation).on('change', showHideRegionLocation);
       });	
    })(window.jQuery);
    
  6. Change the value after id^ to the field that contains the value on which field are being shown/hidden.
  7. The final code looks like this.
    $(document).ready(function()
       {
          $('nobr:contains("Finalized Date")').closest('tr').hide(); 
          $('nobr:contains("Finalized By")').closest('tr').hide();
    });
    
    (function($){
       function showHideRegionLocation() 
       {
       var FeedbackMatchingValue = 'Final';
       
       var thisDiv = $("select[title='Status']"); 
       var mmFieldValue = thisDiv.find("option:selected").text();
    		
       $('nobr:contains("Finalized Date")').closest('tr').hide(); 
       $('nobr:contains("Finalized By")').closest('tr').hide();
    			
       if (mmFieldValue.indexOf(FeedbackMatchingValue) > -1) 
       {
          $('nobr:contains("Finalized Date")').closest('tr').show(); 
          $('nobr:contains("Finalized By")').closest('tr').show();
       } 	
    }
    $(document).ready(function() {
       setTimeout(function() {
          showHideRegionLocation();
       }, 1000);
       $("select[id^='Status'").on('blur', showHideRegionLocation).on('change', showHideRegionLocation);
       });	
    })(window.jQuery);

Adding JavaScript to a form

  1. Open the edit and/or new form of the list.
  2. Set the form in edit mode
  3. Add the Script Editor Web Part to the page
  4. Edit the SNIPPET and add the following code.

    <script src="../../SiteAssets/System/jquery-3.1.1.min.js" type="text/javascript"></script> 
    <script src="../../SiteAssets/System/EditFormHideShow.js" type="text/javascript"></script>
    
  5. Insert the code en Stop editing the form.
  6. Save the custom JavaScript HideColumns and the jQuery script in the correct location.
  7. The JavaScript will now run and hide or shows the field based on the selected value of the field Status.

 

JavaScript / jQuery: Set fields to read only

With SharePoint we use a lot of lists and libraries to store and share information. But not every bit of information needs to be managed/changed by users. Sometimes a workflow or code is responsible for the information. With default SharePoint it is not possible to set field to read only,  but with the help of jQuery and JavaScript we can. We can add JavaScript to the new and or edit form and disable (read only) any field we want. Make sure to disable the quick option, otherwise user will be able to edit the read only field using this feature.

SharePoint 2013/Online: Disable Quick edit

  1. Open the list or library settings
  2. Open the Advanced settings
  3. Set Quick Edit to No

SharePoint 2010: Disable Datasheet editing

  1. Open the list or library settings
  2. Open the Advanced settings
  3. Set Datasheet to No

Creating the JavaScript

  1. Open your favorite JavaScript Editor
  2. Create a new JavaScript file called HideColumns.js
  3. Add the following base code to the JavaScript file
    // A $( document ).ready() block.
    $( document ).ready(function() {
       
    }
    );
    
  4. Now you need to get the display names of the fields you need to set to read only (disable). Note that you need the correct name of the input, select, text area etc fields. Make sure you do not select the label of the field.
  5. You can use a DOM explorer to find the correct type of fields and the corresponding name. Note that different types are just for different columns
  6. In this example I selected the Multiple Lines of text field
  7. The selected code is
  8. In this code you are able to find the name: Multiple Lines
  9. And the type of field: textarea
  10. Do this for all the fields you need disable
  11. In my example I will disable the following fields
    Name Column Type Input field type
    Multiple Lines Multiple lines of text Textarea
    Title Single line of text Input
    Date Date and time Input
    Choice Choice Select
  12. Depended on the type of field different code is required.
  13. For Input and textarea use
    .attr("disabled", "disabled"); 
    
  14. For select we use
    .prop("disabled", true);
    
  15. The final code will look as follows
    // A $( document ).ready() block.
    $( document ).ready(function() {
        jQuery("input[title='Title']").attr("disabled", "disabled"); 
        jQuery("textarea[title='Multiple Lines']").attr("disabled", "disabled");
        jQuery("input[title='Date']").attr("disabled", "disabled"); 	
        jQuery("select[title='Choice']").prop("disabled", true);
        }
    );
    

Adding JavaScript to a form

  1. Open the edit (or new) form of the list.
  2. Set the edit form in edit mode
  3. Add the Script Editor Web Part to the page
  4. Edit the SNIPPET and add the following code

    <script src="../../SiteAssets/System/jquery-3.1.1.min.js" type="text/javascript"></script> 
    <script src="../../SiteAssets/System/HideColumns.js" type="text/javascript"></script> 
    
  5. Insert the code en Stop editing the form.
  6. Save the custom JavaScript HideColumns and the jQuery script in the correct location
  7. The JavaScript will now run and set the required field on read only when the edit form is opened

Show Pictures with Slimbox in SharePoint

Pictures are an important part of a SharePoint site, it enriched the otherwise plain look and feel. With a little extra effort we can integrate Slimbox to show the pictures in a very slick and modern way.

Solution

1. Download Slimbox2 and jQuery, in this example I used jQuery 1.8.3 uncompressed.
2. Save the files in the Style Library of SharePoint. Note that not all the Slimbox files are required to be stored in SharePoint.
3. Include the jQuery javascript, the Slimbox javascript and the Slimbox CSS to the page, page-layout or the master page.

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/slimbox2.js"></script>
<link rel="stylesheet" href="css/slimbox2-rtl.css" type="text/css" media="screen" />

5. Create a picture library and save a couple of pictures to the library. The picture library will provide the necessary thumbnails without any extra effort.
6. Add a CQWP to a page and query the pictures.
7. Create a XSLT that shows the small thumbnails of the pictures, for example in a banner view.

Slimbox Result 1

8. I created two variables for the default SharePoint Thumbnails, Thumbnail_w and Thumnbail_t. And used the following code to show the small thumbnail with a Slimbox link to the bigger thumbnail.

<a href="{$Thumbnail_w}" rel="lightbox" title="{@Title}">
   <img src="{$Thumbnail_t}" alt="alt" class="PhotoAppThumbnail" />
</a>

9. Also note that the title field is added to the Slimbox link, the title will be displayed on the Slimbox overlay.

Result

Slimbox Result 1

SharePoint Default value for multi line column

By default SharePoint gives you the option to set the default column value for a lot of different type of columns. Unfortunately is this option is not available for the multi line column.
But with jQuery and a bit of JavaScript we can! This solution has been create in cooperation with Peter Heibrink.

Solution
1. Download the latest version of jQuery or the compressed jQuery
2. Save the Default Rich Text JavaScript to a JS file

<!-- 	TODO: Set reference to the jQuery.-->
<script type="text/javascript" src="[/...../jquery-1.10.2.min.js]"></script>
<!-- 	TODO: Set the varibale for the fieldname with the display name of the milti line column
	TODO: Set the HTML for the default value-->

<script type="text/javascript">
	jQuery(document).ready(function() {
		var fieldName="Body";
		var defaultText = "<b>Default value</b><br />This is the default rich text value...";
		if(jQuery('nobr:contains(' + fieldName + ')').closest('tr').find('input[id$="TextField_spSave"]').val() == "") {
			jQuery('nobr:contains(' + fieldName + ')').closest('tr').find('input[id$="TextField_spSave"]').val(defaultText);
		}
	});
</script>

3. Save jQuery and Default Rich Text JavaScript somewhere on SharePoint
4. Navigate to the SharePoint list where the multi line column needs a default value
5. Open the advanced library settings and set Launch forms in dialog to No.
DialogYesNo
6. Open the New item page for the list and edit the New item page
7. Add a content editor web part to the page with a Content link to the Default Rich Text JavaScript
ContentLink
8. Save the changed and add a new item!

Result
defaultRichValue

SharePoint 2013 How to add javascript to your site

In SharePoint 2013 is enriched with the Script Editor web part. The web part makes it very easy to add JavaScripts and Jquery script to your SharePoint 2013 site.

Solution

1. Edit the page where you want to use JavaScript.
2. Add the web part Script Editor.
3. Edit the web part Script Editor.

Javascript_2

4. Insert the needed Javascript, in this example the JavaScript will show the current date and time.
Javascript_3
5. Save the changes and  enjoy the result.

Result

Javascript_4