Thursday, December 23, 2010

Using Javascript code to show/hide controls in NewForm or EditForm.

You can use the following javascript code to show/ hide controls in NewForm or EditForm.

< script type="text/javascript" >

_spBodyOnLoadFunctionNames.push("hideFieldsOnStart");

function hideFieldsOnStart() {

//hide the control at startvar control = getTagFromIdentifierAndTitle("input","TextField","FieldDisplayName");

control.parentNode.parentNode.parentNode.style.display="none";

//add an onchange event to the dropdown
getTagFromIdentifierAndTitle("select","DropDownChoice","DropDownDisplayName").onchange = function() {ChangeEvent()};


}


function ChangeEvent()
{

//get the dropdownvar dropdown = getTagFromIdentifierAndTitle("select","DropDownChoice","DropDownDisplayName");

//get the selected valuevar option = dropDown.options[dropDown.selectedIndex].text;

//get the controlvar control = getTagFromIdentifierAndTitle("input","TextField","FieldDisplayName");

//show hide based on your conditionif(option == "xyz")
{
control.parentNode.parentNode.parentNode.style.display="";
}
else
{
control.parentNode.parentNode.parentNode.style.display="none";
}

//this gets the field based on title identifier and tagnamefunction getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
return tags[i];
}
}
returnnull;
}
</script >

List of sharepoint column types and their corresponding identifiers, tagnames and Title


































































SharePoint Field Type Identifier Tag Name Title
Single Line of Text TextField input Same as Field Title
Multiple Lines of Text TextField input Same as Field Title
Number TextField input Same as Field Title
Currency TextField input Same as Field Title
Choice (dropdown) DropDownChoice select Same as Field Title
Lookup (single)* Lookup select Same as Field Title
Lookup (multiple) SelectCandidate; SelectResult select Same as Field Title
Yes/No BooleanField input Same as Field Title
People or Group UserField_downlevelTextBox textarea People Picker

(It must be

People Picker only. Irrespective of Filed name)


It depends what type of field you are trying hide it is in your case
if text field it should be
var control = getTagFromIdentifierAndTitle("input","TextField","FieldDisplayName");

if choice

var control = getTagFromIdentifierAndTitle("select","DropDownChoice","FieldDisplayName");

if yes/no then

var control = getTagFromIdentifierAndTitle("input","BooleanField","FieldDisplayName");

if Lookup then

var control = getTagFromIdentifierAndTitle("select","Lookup","FieldDisplayName");

If it is People Picker


var control = getTagFromIdentifierAndTitle('textarea','UserField_downlevelTextBox','People Picker');

0 comments: