Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

2009/06/23

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);};
}


The original post can be found here: Using Javascript to Manipulate a List Form Field
For a basic function, you could also check out Boris Gomiunik’s Blog for another post about referencing SharePoint form fields using Javascript.

compare dates in sharepoint using JavaScript

you can use the current code to check the differance between dates before saving data using JavaScript code.

The following code I used to use it in case of check dates I hope it will be useful.

function PreSaveAction()

{

var date1 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Letter Date");

var date2 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Decision Date");

var date3 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Request Date");

var arrDate1 = date1.value.split("/");

var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);

var arrDate2 = date2.value.split("/");

var useDate2 = new Date(arrDate2[2], arrDate2[1]-1, arrDate2[0]);

var arrDate3 = date3.value.split("/");

var useDate3 = new Date(arrDate3[2], arrDate3[1]-1, arrDate3[0]);

if(useDate1 >= useDate2)

{

alert("Letter date must be before Decision Date");

return false; // Cancel the item save process

}

else if(useDate2 >= useDate3)

{

alert("Decision Date must be before Request Date");

return false; // Cancel the item save process

}

else

{

return true; // OK to proceed with the save item

}

}

//getTagFromIdentifierAndTitle function

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;

}


2009/06/22

To disable right click on webpage

you can disable the right click on webpage using the following javascript code:

<script language="JavaScript1.1">

<!-- Begin function right(e)

{

if (navigator.appName == 'Netscape' && (e.which == 3 e.which == 2))

return false;

else if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2 event.button == 3))

{

alert(" ");

return false;

}

return true;

}

document.onmousedown=right;

document.onmouseup=right;

if (document.layers) window.captureEvents(Event.MOUSEDOWN);

if (document.layers) window.captureEvents(Event.MOUSEUP);

window.onmousedown=right;

window.onmouseup=right;


// End -->
</script>

2009/06/03

WPSC undefined JavaScript error.


While using Forms Authontication I met the following JS error "WPSC" object isnot defiend, and I added the following code then this error disappeared.


<script type="text/javascript">


if(typeof(WPSC) == "undefined"){


WPSC = new Object();


WPSC.Init = function(){


//do nothing
}


WPSC.WebPartPage = new Object();


WPSC.WebPartPage.Parts = new Object();


WPSC.WebPartPage.Parts.Register = function()


{
//do nothing
}


}


</script>

2009/05/17

Printing WebPage using JavaScript


for printing a webpage using javascript you can use the following code it is very usefull for printing any HTML content.


you can change elem with the content you want to print.


function PrintPage()


{


var elem= myBody();


var popup = window.open(' ','popup','toolbar=no,menubar=no,width=200,height=300');


popup.document.open();


popup.document.write("<html><head><meta name="'WebPartPageExpansion'" content="'full'"></head><body onload="'print()'">");


popup.document.write(elem); popup.document.write("</body></html>");


popup.document.close();


}

2009/03/03

Map of Reusable SharePoint JavaScript

JSRequest



version: WSS 3.0
source file: init.js (ln 1621)
mapped by: Itay Shakury
purpose: provides method to parse query string, filename, and pathname from URL
example:



JSRequest.EnsureSetup();
var qs = JSRequest.QueryString[value];
var fn = JSRequest.FileName;
var pt = JSRequest.PathName;


PreSaveAction()



version: WSS 3.0
source file: n/a (ref: form.js ln 5909)
mapped by: Edin Kapic
purpose: provides hook for creating custom function interrupting submit action
example:



function PreSaveAction(){
var input = getTagFromIdentifierAndTitle("textarea","","Test");
if(input && input.value == "") {
alert("You must complete Test");
return false; // Cancel the item save process
}
return true; // OK to proceed with the save item
}


_spBodyOnLoadFunctionNames



version: WSS 3.0
source file: n/a
mapped by: Sanjay Arora
purpose: Allows you to register additional JavaScript methods that should run in the PageLoad event
example:


_spBodyOnLoadFunctionNames.Push('MyCustomFunctionName');


GetFirstChildElement(e)



version: WSS 3.0
source file: core.js
mapped by: Christophe
purpose: get the first "real" child of a DOM element. This function is useful for Firefox, which interprets a line break as a child element.


GetLastChildElement(e)



version: WSS 3.0
source file: core.js
mapped by: Christophe
purpose: get the last "real" child of a DOM element. This function is useful for Firefox, which interprets a line break as a child element.


GetCBSelectedValues(frm)



version: WSS 3.0
source file: core.js (ln 972)
mapped by: Paul Grenier
purpose: Accepts a form object, loops through all check box elements and returns the values of the checked boxes or false if none are checked.
example:
html


<input id="spUserSelCb_1131" type="checkbox" title="Paul Grenier" onclick="UserSelectionOnClick(this,'1');" value="131" name="spUserSelectionCheckBox_1"/>


JavaScript



var elm = document.getElementsByTagName("form")[0];
GetCBSelectedValues(elm)

Object returned: strList = "131,144,143,7,254,22..."


GetSelectedValue (frmElem)



version: WSS 3.0
source file: init.js (ln 1516)
mapped by: Paul Grenier
purpose: takes a form element with a selectedIndex and returns the selected value or an empty string.


GetSelectedText(frmElem)



version: WSS 3.0
source file: init.js (ln 1523)
mapped by: Paul Grenier
purpose: takes a form element with a selectedIndex and returns the selected text or an empty string.


escapeProperly(str)



version: WSS 3.0
source file: init.js (ln 168)
mapped by: Paul Grenier
purpose: takes any string and returns a URL-encoded string.
example:
escapeProperly("this is a test")


"this%20is%20a%20test"


unescapeProperly(str)



version: WSS 3.0
source file: init.js (ln 855)
mapped by: Paul Grenier
purpose: takes any URL-encoded string and returns a string.
example:
unescapeProperly("this%20is%20a%20test")


"this is a test"



refrance : http://sharepointdevwiki.com/display/public/SharePoint+JavaScript+Functions+Overview

2009/03/02

Hide fields in NewForm.aspx without customization


You can use the following techniqe to hide flags that you add in custom list or document library without customization you can add the following code after the ContentPlaceHolder tage


<asp:Content ContentPlaceHolderId=”PlaceHolderMain” runat=”server”>


The script as the following:


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

// set the function that will load in the page call.


_spBodyOnLoadFunctionNames.push("hideFields");


//the function that will search for control


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



// this function wil hide the controls by field Name



function hideFields()
{
var control = findacontrol("Hired");
control.parentNode.parentNode.style.display="none";
control = findacontrol("inServe");
control.parentNode.parentNode.style.display="none";
control = findacontrol("Title");
control.parentNode.parentNode.style.display="none";
}


</script>


you can change the Green text with your controls name that you need to hide

2009/02/22

TextBox accepts only numbers


<asp:TextBox " runat="server" id="txt1" onkeypress="return isNumberKey(event)" />

This is the javascript method that will be called by the textbox on onkeyPress event
<SCRIPT type="text/javascript" language=Javascript>

<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>

2009/02/14

Get SelectedValue from sharepoint lookup Field


<SharePoint:FormField runat="server" id="ff30{$Pos}" ControlMode="New" FieldName="_x0627__x0644__x0628__x0646__x06" __designer:bind="{ddwrt:DataBind('i',concat('ff30',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@_x0627__x0644__x0628__x0646__x06')}" />

<SharePoint:FieldDescription runat="server" id="ff30description{$Pos}" FieldName="_x0627__x0644__x0628__x0646__x06" ControlMode="New"/>

To get the selectedvalue from sharepoint lookup field you follow these steps.

first you need to assign event onchange to this field.


<script type="text/javascript" language="javascript">
//Select the method that will run at the sharepoint page body load

_spBodyOnLoadFunctionNames.push('setEvent');

//set event function
function setEvent()
{
var selectBank= document.getElementById('ctl00_m_g_8f64049a_17a6_4a6d_89a3_c227374a7f7a_ff30_1_ctl00_Lookup');

//eventName and method that will call
selectBank.setAttribute('onchange',checkBank);


}

//function will call when event is fired
function checkBank()
{
var selectBank= document.getElementById('ctl00_m_g_8f64049a_17a6_4a6d_89a3_c227374a7f7a_ff30_1_ctl00_Lookup');
var selectedValue=selectBank.options[selectBank.selectedIndex].value;
alert(selectedValue)

}

</script>


Get SelectedValue Of dropdownlist


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

var s1= document.getElementById('Select1');

var selectedValue=s1.options[s1.selectedIndex].value;

alert('selectedValue');


</script >

2009/02/08

Getting Vlaue of UserField In Sharepoint using JavaScript


If you need to get the value of userFiled control using javascript.

<SharePoint:FormField runat="server" id="ff2{$Pos}" ControlMode="New" FieldName="_x0627__x0644__x0631__x0642__x06" __designer:bind="{ddwrt:DataBind('i',concat('ff2',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@_x0627__x0644__x0631__x0642__x06')}"/>



<SharePoint:FieldDescription runat="server" id="ff2description{$Pos}" FieldName="_x0627__x0644__x0631__x0642__x06" ControlMode="New"/>



you can search for this ID in viewsource you can find many controls one of these controls is Span it's ID will be in my case



"ctl00_m_g_271a3a52_3741_466d_80b4_eb05da86cc05_ff2_1_ctl00_ctl00_UserField"



you can use the following code to preview the value of the control



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

function CheckUser()

{

var selectedUser= document.getElementById('ctl00_m_g_271a3a52_3741_466d_80b4_eb05da86cc05_ff2_1_ctl00_ctl00_UserField').innerText; alert(selectedUser); return false;

}

</script>




This control contains the value of this field

It will breview the following value
then you can use this value in filteration or any other Issue





2009/02/07

SharePoint Built-in JS Functions


//Get Current User ID
_spUserIdex:
alert(_spUserId);

//Run JS Function on Page Load
_spBodyOnLoadFunctionNames.push(' FunctionName ');

//First we must call the EnsureSetup method
JSRequest.EnsureSetup();

//Get a query string parameter called ItemId. i.e - "page.aspx?ItemId=11" will return 11
itemId = JSRequest.QueryString["ItemId"];

//Get the current page name. i.e - "default.aspx"
itemId = JSRequest.FileName;

//Get the current path name. i.e - "/doclib/default.aspx"
itemId = JSRequest.PathName;