Wednesday, February 10, 2010

JavaScript for SharePoint List field to populate data from query strings

Following JavaScript is used to Hide/Show the SharePoint List Fields based on DropDown Value:-

<script language="javascript" type="text/javascript">

function findacontrol(FieldName) {

var arr = document.getElementsByTagName("!");

// get all comments

for (var i=0;i < arr.length; i++ )

{

// now match the field name

if (arr[i].innerHTML.indexOf(FieldName) > 0)

{ return arr[i]; }

}

}

function hideFields() {

var control = findacontrol("Number of Styles on Floor");

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

}

function showFields() {

var control = findacontrol("Number of Styles on Floor");

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

}

function footwear_hideFields() {

var control = findacontrol("Class");

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

control = findacontrol("Core Call Outs");

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

}

function footwear_showFields() {

var control = findacontrol("Class");

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

control = findacontrol("Core Call Outs");

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

}

</script>


 

<script type="text/javascript">

function getField(fieldType,fieldTitle) {

var docTags = document.getElementsByTagName(fieldType);

for (var i=0; i < docTags.length; i++) {

if (docTags[i].title == fieldTitle) {

return docTags[i]

}

}

}

function syncDropDowns() {

selectedId = getField('select','Division').options[getField('select','Division').selectedIndex].value;

if (selectedId == '1'){

hideFields();

footwear_hideFields();

//alert(selectedId);

}

if (selectedId == '2'){

showFields();

footwear_hideFields();

//alert(selectedId);

}

if (selectedId == '3'){

hideFields();

footwear_showFields();

//alert(selectedId);

}

}

// how add a function to Sharepoint field controls

getField('select','Division').onchange = function() {syncDropDowns()};

</script>

Following JavaScript is used to Hide the SharePoint List Fields

<script language="javascript" type="text/javascript">

_spBodyOnLoadFunctionNames.push("hideFields");

function findacontrol(FieldName) {

var arr = document.getElementsByTagName("!");

// get all comments

for (var i=0;i < arr.length; i++ )

{

// now match the field name

if (arr[i].innerHTML.indexOf(FieldName) > 0)

{ return arr[i]; }

}

}

function hideFields() {

// Here we call controls to hide using findcontrol function

var control = findacontrol("Class");

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

}

</script>

Following JavaScript is used to Set the SharePoint List Fields Using Query String Parameter:-

<script type="text/javascript">

_spBodyOnLoadFunctionNames.push("fillDefaultValues");

function fillDefaultValues() {

    var qs = location.search.substring(1, location.search.length);

    var args = qs.split("&");

    var vals = new Object();

    for (var i=0; i < args.length; i++) {

var nameVal = args[i].split("=");

var temp = unescape(nameVal[1]).split('+');

nameVal[1] = temp.join(' ');

vals[nameVal[0]] = nameVal[1];

}

// setLookupFromFieldName("Division", vals["Division"]);

setChoiceFromFieldName("Division", vals["Division"]);


// To set Hyper Link Default Value Use this function

// getTagFromIdentifierAndTitle("input","URLFieldURL","FieldName");

}


 

function setLookupFromFieldName(fieldName, value) {

if (value == undefined) return;

var theSelect = getTagFromIdentifierAndTitle("select","Lookup",fieldName);

if (theSelect == null) {

var theInput = getTagFromIdentifierAndTitle("input","",fieldName);

ShowDropdown(theInput.id);

var opt=document.getElementById(theInput.opt);

setSelectedOption(opt, value);

OptLoseFocus(opt);

} else {

setSelectedOption(theSelect, value);

}

}

function setSelectedOption(select, value) {

var opts = select.options;

var l = opts.length;

if (select == null) return;

for (var i=0; i < l; i++) {

if (opts[i].value == value) {

select.selectedIndex = i;

return true;

}

}

return false;

}

//Below Function is used to Set TextField Values, Hyper link values

function 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];

}

}

return null;

}

//Below Function is used to Set Choice Values like DropDownChoice

function setChoiceFromFieldName(fieldName, value) {

if (value == undefined) return;

var theSelect = getTagFromIdentifierAndTitle("select","DropDownChoice",fieldName);

setSelectedOption(theSelect, value);

}

//Below Function is used to Set Date and Time field

function setDateFromFieldName(fieldName, value) {

if (value == undefined) return;

var theInput = getTagFromIdentifierAndTitle("input","DateTimeFieldDate",fieldName);

theInput.value=value

}

</script>


 

FOR Hyperlink Field

Tag name- input  

Identifier- URLFieldURL

And just remember that if you are defaulting the Hyperlink field to a local link on the system.

Replace "\" with "/"

For ex: "\\pbosfile06\policy\Application" Change that to "//pbosfile06/policy/Application". It would now work fine without any problem.

For setting date time hour and minute fields

Here is a workarround for setting the values for start/end hours and start/end minute in a Task form. Since the ID for those select contros is generated dinamically i've implemented 2 functions which search for the ones that have the string "00:" for hours and "05" for minutes. I know it's not an elegant way to do it but it will have to do until i can find a way to get the ID for those controls. (Hopefully SP will always render the controls in the same order, because otherwise the values will get set in the wrong order).

   function setHours(startHour, endHour) {

 var tags = document.getElementsByTagName("select");

 var value = startHour;

     for (var i=0; i < tags.length; i++) {

       var select  = tags[i];

       if (select != null && select.options!=null && select.options[0] != null){

           if (select.options[0].value.indexOf("00:") >= 0 ) {

                setSelectedOption(select, value);

            value = endHour;

           }

       }

 }

   }

   function setMinutes(startMinute, endMinute) {

 var tags = document.getElementsByTagName("select");

 var value = startMinute;

     for (var i=0; i < tags.length; i++) {

       var select  = tags[i];

       if (select != null && select.options!=null && select.options[0] != null){

           if (select.options[1].value.indexOf("05") >= 0 ) {

               setSelectedOption(select, value);

            value = endMinute;

           }

       }

 }

   }

For example, a call would be:

     setHours("09:", "10:");

     setMinutes("05, "10");

Remember to append the ":" for the hour fields!


 

For setting Yes or No Form Fields

function setYesNoFrimFieldId(id, value)

{

  if (( value == undefined) || ( id == undefined) return;

  var b = document.getElementById( id );

  var newBoolean = false ;

  var newOnOffVal = "off";

  if ( value == 1 || value == true || value == "true" )

  {

       newBoolean = true ;

       newOnOffVal = "on";

  }

  b.checked = newBoolean ;

  b.value = newOnOffVal ;

}


 

Embed a text into RTE (Rich Text Editor)

When I needed to embed some text into RTE in a custom list form. I didn't find any standard or clean a solution for it. I must tried various things and this is my solution for it. :)

<script language="javascript" type="text/javascript">
<!--
function getField(fieldType, fieldTitle) {
var docTags = document.getElementsByTagName(fieldType);
for (i = 0; i < docTags.length; i++) {
if (docTags[i].title == fieldTitle) {
return docTags[i]
}
}
}

function embedText(newText) {
var fieldID= getField("textarea", "Content").id;
RTE_GiveEditorFocus(fieldID);
RTE_SaveSelection(fieldID);
RTE_GetSelection(fieldID).pasteHTML(newText);
}
--//>
</script>


 

Using Javascript to access a List Form Field in SharePoint Designer

An article was posted showing how to access and manipulate a List Form Field within SharePoint Designer using Javascript over at Microsoft SharePoint Designer Team Blog. The code in the article supported the following types of SharePoint 2007 form fields, but not the Radio Buttons Choice field:

Single Line of Text

Multiple Lines of Text

Number

Currency

Choice (dropdown)

Lookup (single)

Lookup (multiple)

Yes/No

So I've modified the function getTagFromIdentifierAndTitle and added onto it the code to allow accessing Radio Buttons Choice fields. The following is the modified function:

/*******

SharePoint Field Type     identifier         tagName         Option

---------------------    --------------    ----------    ---------

Single Line of Text     TextField     input

Multiple Lines of Text TextArea     input

Number             TextField     input

Currency         TextField     input

Choice (radio buttons)    RadioButtons    input

Choice (radio buttons)    RadioButtons    input         value

Choice (dropdown)     DropDownChoice     select

Lookup (single)*    Lookup         select

Lookup (multiple)     SelectCandidate;

            SelectResult     select

Yes/No            BooleanField     input

******/

function getTagFromIdentifierAndTitle(tagName, identifier, title, option) {

var len = identifier.length;

var tags = document.getElementsByTagName(tagName);

for (var i=0; i < tags.length; i++) {

var idString = tags[i].id;

var nameString = tags[i].name;

// get selected radio button value only

if (option == "value" && tags[i].type == "radio" && (identifier == "RadioButtons" && nameString.indexOf(identifier) == nameString.length - len)) {

var tagParentHTML = tags[i].parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.innerHTML;

     if (tagParentHTML.indexOf('FieldName="'+title+'"') > -1) {

         var radioButtons = document.getElementsByName(nameString);

         var radioValue = "";

         for (var x=0; x < radioButtons.length; x++) {

          if (radioButtons[x].checked) {

              radioValue = radioButtons[x].parentElement.title;

          break;

          }

         }

var o = document.createElement("INPUT");

o.type = "hidden";

o.value = radioValue;

    return o;

     }

}

// get radio buttons group

if (tags[i].type == "radio" && (identifier == "RadioButtons" && nameString.indexOf(identifier) == nameString.length - len)) {

var tagParentHTML = tags[i].parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.innerHTML;

     if (tagParentHTML.indexOf('FieldName="'+title+'"') > -1) {

         return document.getElementsByName(nameString);

     }

}

    // all other input or select type

else if (tags[i].title == title && (identifier == "" || idString.indexOf(identifier) == idString.length - len)) {

return tags[i];

}

}

return null;

}

Here is how you would use the function above for Radio Buttons:

// to get the selected radio button and its value

var myRadioButtonsSelected = getTagFromIdentifierAndTitle("input","RadioButtons","MyFieldName","value");

var myRadioButtonsValue = myRadioButtonsSelected.value;

 
 

// to get the array for radio buttons

var myRadioButtonsArray = getTagFromIdentifierAndTitle("input","RadioButtons","MyFieldName");

for (var x=0; x < myRadioButtonsArray.length; x++) {

// do whatever you like here...

// for example:

myRadioButtonsArray[x].parentElement.onclick = function(){alert(myRadioButtonsArray[x].value);};

Couple of useful JavaScript global variables in SharePoint

If you're using custom JavaScripts with SharePoint some global JavaScript variables may come in handy.

These variables work if you're using SharePoint's default or any other custom master page.

L_Menu_BaseUrl - the base URL of the site / subsite. Very useful when you need to determine the absolute path of the site in JavaScript. Example: document.location = L_Menu_BaseUrl + 'lists/calendar/allitems.aspx' //redirects to Calendar list

L_Menu_LCID - the LCID of the site you're in. Useful if you need to determine the language of the site. The list of Locale IDs can be found here. I'm using the LCID for localizations in ERTE project. See the example of checking LCID below:
.
L_Menu_SiteTheme - the name of the theme applied to the site.

There is one more useful variable, but this one can't be used on custom master pages that you created. This one is used in the SharePoint's default pages:

_spUserId - the ID of the logged in user.


 

Add functions and events to SharePoint form fields


 

Do you sometimes wish to make some special form validation or other javascript actions on SharePoint form fields (like for example onchange, onfocus, onblur, etc?). You can add special functions on events to the SharePoint form fields using JavaScript. All you need to do is

1. Write your JavaScript function
2. Use the getField function I was writing about to refference the SharePoint Fiedl
3. write the following code:

getField('[field_type]','[field_title]').[event] = function() {[function_name]};

Let me demonstrate in an example below. I have a SharePoint List with a field "Menu" that is a lookup field to Title list "Menu". I've created another field "Menu_id" that is a lookup to the same list, but instead of Title it should select the ID. These two fields need to select the same item from the list Menu.

Now we'll prepare a one-way synchronization. We'll want those two fields synchronized when selecting the item from the "Menu" dropdown. So we'll add an "onchange" event to the "Menu" select field.

1. Add a Content Editor Web part to the page using this method

2. Edit the Source of the content editor web part add the script code, insert the getField function, write your function and use function above. The full code is below

<script type="text/javascript">
function getField(fieldType,fieldTitle) {
    var docTags = document.getElementsByTagName(fieldType);
    for (var i=0; i < docTags.length; i++) {
        if (docTags[i].title == fieldTitle) {
            return docTags[i]
        }
    }
}

function syncDropDowns() {
selectedId = getField('select','Menu').options[getField('select','Menu').selectedIndex].value;
for (i=0; i<getField('select','Menu_id').options.length; i++) {
  if(getField('select','Menu_id').options[i].value == selectedId) getField('select','Menu_id').options[i].selected='selected';
}
}

getField('select','Menu').onchange = function() {syncDropDowns()};

</script>

This is an example made with CEWP and in the SharePoint. The same works also in the Data View Webpart.

Quickly filter a List/Document Library View using URL

This one's very useful when you're having a lot of items in a list or document library and you need a quick filter.

If you'll select the filter field it can happen that it will load for a long time. So lately I'm using URL. Suppose you have a long list of contacts and you need to find a contact named Boris.

In the AllItems.aspx - view of the page, add parameters

?FilterField1=[Field Name]&FilterValue1=[Value]

You can add more filterfield and filtervalue parameters to apply filters to more fields (FilterField2, FilterValue2, ...)

The only trick is to know the Field Name like it's saved in SharePoint. You can see this in the list settings page (click on a column name and check URL) or just make a manual filter for the first time.

In my case to find a contact with First Name Boris, I'd go to

http://[site_URL]/lists/contacts/AllItems.aspx?FilterField1=FirstName&FilterValue1=Boris

I'm always browsing a document library with filtering by specific document type. So I've created a simple script. Just add a Content Editor Webpart to your homepage, edit its source and add the following code (just update the url to your document library (docLibUrl):

<script type="text/javascript">
function docLib(dropdown) {
  var vtype = dropdown.options[dropdown.selectedIndex].value;
  var docLibUrl = "/Shared Documents/Forms/AllItems.aspx";
  var filterField = "DocIcon"
  if (vtype != 'Select') {
    document.location=docLibUrl+"?FilterField1="+filterField+"&FilterValue1="+vtype;
  }
}
</script>
<select style="margin:10px; 0px;" id="DocumentTypes" onchange="docLib(this)">
<option value="Select">Select document type</option>
<option value="Select">-- Office 2007 --</option>
<option value="docx">Word 2007</option>
<option value="xlsx">Excel 2007</option>
<option value="pptx">PowerPoint 2007</option>
<option value="Select">-- Office 2003 --</option>
<option value="doc">Word 2003</option>
<option value="xls">Excel 2003</option>
<option value="ppt">PowerPoint 2003</option>
<option value="Select">-- Other --</option>
<option value="pdf">Acrobat (PDF)</option>
</select>

0 comments: