Hiding and Showing Fields Based on Value Selected in Drop Down using JQuery in SharePoint 2013

Hiding and showing fields based on value selected in drop down using Jquery in SharePoint 2013.

Assumptions:

  1. SharePoint list called “Student”.
  2. A Choice field called “Student Type” (drop down) with values as ‘University’ and ‘School’.
  3. Some single line text fields “University”, “School”, “Class”, “Year”.

Steps:

  1. Open the newform.aspx page of a list.\
  2. Edit the page.
  3. Add a new script editor webpart.
  4. Add the below code to the script editor webpart.

  1. <script src="/sites/SiteAssets/jquery-1.10.2.js"></script>  
  2. <script src="/sites/SiteAssets/sputility.min.js"></script>  
  3.   
  4. <script language="javascript" type="text/javascript">  
  5.     $(document).ready(function() {  
  6.   
  7.         // Gets the Student type field  
  8.         var studentType = SPUtility.GetSPField('Student Type');  
  9.   
  10.         // creates a function to show or hide University field or School field  
  11.         var showOrHideField = function() {  
  12.             var studentTypeValue = studentType.GetValue();  
  13.   
  14.             // Hide the City field if the selected value is Other  
  15.             if (studentTypeValue == 'University’) {  
  16.                 SPUtility.HideSPField('School'); SPUtility.HideSPField('Class');  
  17.             } else {  
  18.                 SPUtility.ShowSPField('School');  
  19.                 SPUtility.ShowSPField('Class');  
  20.             }  
  21.         };  
  22.   
  23.         // run at startup (for edit form)  
  24.         showOrHideField();  
  25.   
  26.         // make sure if the user changes the value we handle it  
  27.         $(tudentType.Dropdown).on('change', showOrHideField);  
  28.     });  
  29. </script>  
Explanation:

 

  1. Reference needs to be made to jquery and SPUtility.js files.
  2. GetSPField(‘<parameter>’): Gets the SharePoint list field.
  3. GetValue(): Gets the selected value from the drop down list.
  4. SPUtility.HideSPField('School'): This will be hiding the fields.
  5. SPUtility.ShowSPField('Class'): This is be showing the fields.
Ebook Download
View all
Learn
View all