Pages

Wednesday, February 9, 2011

Hiding Form Controls on selection Change in a Custom List Form (Attach Javascript to Form Controls) – No Server Side Code

Here is a very Simple requirement which many users would like to have it. Say for instance when the New Item Form of a SharePoint List is loaded, the user would be displayed with all the controls (Form Controls), among these controls we have a Choice field of type radio button and Titled “Location”. The values in the Choice Field read as “USA” and “Other”.

So if he user selects “USA” we need to display another Choice Field of type “Dropdown” Titled “State” (which contains all states of USA) and display a Multiline Textbox to Key in Country, State when “others” is selected**. The data should be saved back to the List

To do this we first we need to create a Custom List Form (Creating a Custom List Form is out of scope of this post). Place the form in a Table (if you don’t have a Table already) and ID as ’tblDataTable‘. Now add ID’s to the rows which contains the controls to be hidden and shown. In this example I have it as ‘trLocation‘ and ‘trNote‘. Once we are done with it, we need to attach a Javascript fucntion to the Radio Button: The code marked in Brown color below is how we attach the javascript function to the click event:

<script type="text/javascript" language="javascript">
_spBodyOnLoadFunctionNames.push("hideLocations");
function hideLocations()
{
var vTblDataRow = document.getElementById('tblDataTable');
document.getElementById('trLocation').style.display = 'none';
document.getElementById('trNote').style.display = 'none';
if(typeof(vTblDataRow) != 'undefined')
{
var vControls = vTblDataRow.getElementsByTagName('input');
if(vControls.length > 0)
{
for(var i=0; i < vControls.length; i++)
{
if(vControls[i].type == 'radio')
{
vControls[i].onclick = function NewFunction()
{
var vlblRadioValue = this.nextSibling;
if(vlblRadioValue.innerText == 'USA')
{
document.getElementById('trLocation').style.display = 'block'; document.getElementById('trNote').style.display = 'none';
}
else if(vlblRadioValue.innerText == 'Others')
{
document.getElementById('trNote').style.display = 'block'; document.getElementById('trLocation').style.display = 'none';
}
else{//Add additional functionality if you wish}
}
}
}
}
}
}
</script>


Add this Code to the page which hosts the Custom List Form or alternatively you can add a content Editor WebPart which holds this code and you are all set to go.


Note: You may have to add few more additional lines of code to in those if else conditions to satisfy more requirements such as the Dropdown Containing State should not be updated after clicking “Ok” (Submit) Button when “Others” is selected. so in the Conditional braching we need to clear of the selection for State Dropdown.


Thanks for Visiting my blog!


**This is just an example and the actual requirement can be more realistic.