I had to figure out a way to get a drop-down field to filter based on the selection of a first. I knew and researched that you can purchase a 3rd party tool to do that, but most were overkill, and very expensive. I only needed the dependent\cascading dropdown piece, not the other bells and whistles that came with their expensive products. Especially for SharePoint online.
Most tools or add-ons you have to 'subscribe' to and now it's a recurring expense. Nope! Not for me... :-)
Some preliminary notes:
I cannot include this part in the script because the way you show\hide fields in SharePoint Online. You have to inspect the field using the DOM inspector and get the unique 'ct1' field ID.
It would look something like this if it is a "Checkbox" type field.
var payroll = document.getElementById('ctl00_ctl46_g_f9bbc609_c63b_4ac2_9abf_6499c1d1112e_ff151_ctl00_ctl00_BooleanField')
Then you could just use payroll.hide() or payroll.show() to hide or show accordingly
That tangent aside, onto the real meat of this article.
Prerequisites:
Debugging\Troubleshooting
If the script doesn't work right away, you can uncomment the 3 "Alert" lines by removing the leading forward slashes (//) and it'll let you know where it's at in the code and might point you to what's not firing off.
The Source Code
<script src="/SiteAssets/Javascript/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
//alert ("I Am Ready");
$("select[title^='Department']").change(function()
{
SetCostCenterDropDownList();
});
});
function SetCostCenterDropDownList(){
var department =$("select[title^='Department']").val();
//get a reference to the child drop-down to load new values below
var costCenterSelection = $("select[title='Cost Center Required Field']");
switch (department)
{
case 'Department1':
costCenters = ['','123','456','789','012','345'];
break;
case 'Department2':
costCenters = ['','987','654','321'];
break;
case 'Department3':
costCenters = ['','208','582','963'];
break;
default:
alert("No Associated Cost Centers");
break
}
//alert(costCenters);
//clear out existing options from Cost Centers drop-down
$("select[title='Cost Center Required Field']")
.find('option')
.remove();
//Add new cost centers to dropdown
$.each(costCenters, function (index,value)
{
//alert(value);
costCenterSelection.append('<option value="' + value + '">' + value + '</option>');
});
};
</script>
There you go. A simple yet effective dependent drop-down that's free. What I've outlined is really just the tip of the iceberg with what's possible. Multiple dependencies, showing and hiding fields, prepopulating fields are just some of the enhancements you can add to this. Making the form easier to fill in for users makes them happy and avoids errors which makes admins happy. 😀
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)