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