This project has moved and is read-only. For the latest updates, please go here.

Hide/Show Fields sp2013

Apr 23, 2014 at 8:44 PM
Hi Kit -
Have there been any reported issues using a custom list in SP 2013 to hide fields?

here's my code snippet. The City field is hidden when the new form displays but won't show when I change the Country field

<script type="text/javascript" src="http://i-myconnect.coverys.com/SiteAssets/jquery-1.11.0.min.js"></script>
<script src ="http://i-myconnect.coverys.com/SiteAssets/sputility.min.js"></script>
<script> $(document).ready(function(){ // ----- Hide the field at the begin if the default value is other. // Get a single select dropdown field var countryField = SPUtility.GetSPField('Country'); var countryFieldValue = countryField.GetValue(); // Hide the City field if the selected value is Other if(countryFieldValue == 'Other') { SPUtility.GetSPField('City').Hide(); } else{ SPUtility.GetSPField('City').Show(); } // ----- Hide/Show the field based on new selected value. var id = SPUtility.GetSPField('Country').Dropdown.id; $('#'+id).on('change', function() { if (countryFieldValue == 'Other') { SPUtility.GetSPField('City').Hide(); } else { SPUtility.GetSPField('City').Show(); } }); }); </script>
Apr 26, 2014 at 6:55 PM
Edited Apr 26, 2014 at 6:55 PM
Joe,
Sorry, been busy. I've refactored your code a little bit:
<script type="text/javascript" src="/SiteAssets/jquery-1.11.0.min.js"></script> 
<script type="text/javascript" src="/SiteAssets/sputility.min.js"></script>
<script>
function OnCountryFieldDropdownChange(spfield) {
    var countryFieldValue = spfield.GetValue(); 
    // Hide the City field if the selected value is Other 
    if(countryFieldValue === 'Other') { 
        SPUtility.GetSPField('City').Hide(); 
    } else{ 
        SPUtility.GetSPField('City').Show(); 
    } 
}

$(document).ready(function(){ 
    // Get a single select dropdown field 
    var countryField = SPUtility.GetSPField('Country');
    
    // whenever the field's dropdown changes, check whether we need to show or hide
    $(countryField.Dropdown).on('change', function() { 
        OnCountryFieldDropdownChange(countryField);
    });
    
    // run it once when the form loads to show/hide the field
    OnCountryFieldDropdownChange(countryField);
}); 
 </script>
Couple of changes:
  • Use relative paths to your .js files, it'll help if your site is http/https
  • SharePoint 2013 field IDs have really funky values so your selector for jQuery was not working. Either way, you don't need it since there is already a reference to the element (the Dropdown property)!
  • Use a function for the same logic (showing or hiding city field) so you only have to change your code one place!
Hopefully this helps!
Thanks,
Kit