All About SharePoint

Liedong(Ken) Zheng,SharePoint Leader at SIMPLOT

Posts Tagged ‘JavaScript’

Dynamically Add HTML Element To SharePoint

Posted by ken zheng on January 21, 2009

I have played with the javascript for Item ID in display and edit forms. The interesting part is you can add row into table by Javascript.

<script type="text/javascript">
//
// Item ID in DispForm.aspx and EditForm.aspx
// Feedback and questions: Christophe@PathToSharePoint.com
//
function DisplayItemID()
{
var regex = new RegExp("[\\?&]"+"ID"+"=([^&#]*)");
var qs = regex.exec(window.location.href);
var TD1 = document.createElement("TD");
TD1.className = "ms-formlabel";
TD1.innerHTML = '<h3 class="ms-standardheader">Issue ID</h3>';
var TD2 = document.createElement("TD");
TD2.className = "ms-formbody";
TD2.innerHTML = qs[1];
var IdRow = document.createElement("TR");
IdRow.appendChild(TD1);
IdRow.appendChild(TD2);
var ItemBody = GetSelectedElement(document.getElementById("idAttachmentsRow"),"TABLE").getElementsByTagName("TBODY")[0];
ItemBody.insertBefore(IdRow,ItemBody.firstChild);
}

_spBodyOnLoadFunctionNames.push("DisplayItemID");
</script>

Posted in JavaScript, Sharepoint | Tagged: , | 5 Comments »

Calling UserControl’s Event in ASP .NET Page By AJAX

Posted by ken zheng on September 19, 2008

If you have a usercontrol which has a button click event and you want to raise a postback like the button is clicked.

User Control code to declare a global variable in javdsciprt for Postback

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        MyBase.OnLoad(e)

        Dim sm As ScriptManager = ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "ClientID", String.Format("var logoutClientId = '{0}$LogoutLink';", Me.ClientID.Replace("_", "$")), True)

    End Sub

    Public Sub LogoutLink_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LogoutLink.Click
        Page.LogoutCurrentUser("Sucessfully logged out.")
    End Sub

The below javascipt is to logout when a full postback raised.

window.onunload = function(){ unloadPageAndError();}

var loader = function(sender, args) { 
    if(!args.get_isPartialLoad()){
        PageMethods.CheckLogin(function(result){
            if(result)
            {
                unloadPageAndError();
            }    
        },
        function(error)
        {
            unloadPageAndError();
        }
        );    
    }
}

var unloadPageAndError = function()
{
    <strong>__doPostBack(logoutClientId,'')</strong>
}

Sys.Application.add_load(loader);

Below is a Web Method in your web page, you need to enable your scriptmanger.enablepagemethod = true

    <System.Web.Services.WebMethod()> _
    Public Shared Function CheckLogin() As Boolean
        Return UserContext() Is Nothing
    End Function

Posted in .Net | Tagged: , | Leave a Comment »

Register JavaScripts in 2 ways

Posted by ken zheng on September 19, 2008

You can register your JavaScript in server side by 2 ways

        ' The very first control added to the form must be the AJAX script manager.
		Dim cl As ClientScriptManager = Me.ClientScript
		Dim cstype As Type = Me.GetType()

		cl.RegisterClientScriptInclude(cstype, "DefaultScript", ResolveClientUrl("~/JScript Files/Test.js"))
       

        myScriptManager = New ScriptManager
        myScriptManager.ID = "__PageScriptManager"
        myScriptManager.EnablePageMethods = True

        myScriptManager.RegisterStartupScript(Me, GetType(Page), "StartManualTearDownScript", "manualTearDown.init();", True)

        If Me.PageAccess = PageAccessType.SecurePage Then
            Dim ref As New System.Web.UI.ScriptReference("JScript Files/Secure.js")
            myScriptManager.Scripts.Add(ref)
        End If

        myScriptManager.AsyncPostBackTimeout = WebConfigurationHelper.AsyncPostBackTimeout

        myHtmlForm.Controls.Add(myScriptManager)

Posted in .Net | Tagged: | Leave a Comment »

Bring a Yes/No Dialog box when Back Button is clicked in Broswer

Posted by ken zheng on July 28, 2008

Add

<SCRIPT LANGUAGE="JavaScript1.2" TYPE="text/javascript">
<!--
window.onbeforeunload = unloadMess;
function unloadMess(){
	mess = "Thanks for visiting.\nYou will now be returned to our regularly scheduled program."
	return mess;
}
//-->
</SCRIPT>


before your html body.

But there is a issue as the the event can be invoked using the form submit method. which is
the ‘__doPostBack’ script and it contains the line
‘theform.submit()’.

And I just found a way you can detect if it is the Back button clicked by

 <script>
 function onBeforeUnloadAction(){
   return "Think twice before you leave!";
 }
 window.onbeforeunload = function(){
   if((window.event.clientX<0) ||
      (window.event.clientY<0)){
     return onBeforeUnloadAction();
   }
 }
 </script>

The way to avoid it is that you add a client click script to set event.cancelBubble property to true. Here is some code:

	Page.ClientScript.RegisterStartupScript(typeof(String), "ConfirmClose", @"
	<script>
                var postback= false;
		window.onbeforeunload = confirmExit;
		function confirmExit()
		{
		if(postback == true)
			event.cancelBubble = true;
		else
			return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons."";												
		}     
	</script>");

VB .NET

Page.ClientScript.RegisterStartupScript(GetType(String), "ConfirmClose", "" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "<script>" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "var postback= false; window.onbeforeunload = confirmExit;" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "function confirmExit()" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "{" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "if(postback == true)" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "event.cancelBubble = true;" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "else" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons."";" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "} " & Chr(13) & "" & Chr(10) & "" & Chr(9) & "</script>")

then my save button contains the following aspx markup:

OnClientClick="postback=true;return true;"

http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript

http://www.webreference.com/dhtml/diner/beforeunload/bunload4.html

Posted in Uncategorized | Tagged: | Leave a Comment »

See if page is valid from JavaScript

Posted by ken zheng on July 2, 2008

I did a little digging through the javascript code that ASP.Net uses to do its client-side (javascript) validation to figure out how ASP.Net knows if the page or group is valid or not before submitting the form. Here is the hack you can use to do it yourself.

// a empty string means page. 
var validationGroupName = "";

if (typeof(Page_ClientValidate) == 'function')
{
var validationResult = Page_ClientValidate(validationGroupName);

if (validationResult == true)
{
// do your cool javascript stuff here. This will only happen if the page or group is valid
}
}

Posted in Uncategorized | Tagged: | 1 Comment »

CheckBox and CheckBoxList Validators for multiple checkboxlists

Posted by ken zheng on June 27, 2008

Use 4Guys Creating CheckBox and CheckBoxList Validators in ASP.NET 2.0, you can build a custom validator control for your Checkbox and checkboxlist. But if you have more than one CheckBoxList in your page, the validator will not work because the Javascript will only apply to one control.

What you can do is modify the validator class to create an individual javascript for each validator.

In GenerateClientValidation method

change to:

….

Attributes["evaluationfunction"] = "VerifyItemSelected_" + <strong>ControlToValidate</strong>;

StringBuilder scriptBuilder = new StringBuilder();

scriptBuilder.Append(@"&lt;script language='javascript'&gt;");
scriptBuilder.Append(string.Format("function VerifyItemSelected_{0}", <strong>ControlToValidate</strong>));
scriptBuilder.Append(@"() {");
scriptBuilder.Append(string.Format("var targetControlName = document.getElementById('{0}')", this.ClientID));
scriptBuilder.Append(@".controltovalidate;");

…..

Finally,

Page.ClientScript.RegisterClientScriptBlock(typeof(CheckBoxListValidator), “CustomCheckboxListValidationScript_” + ControlToValidate, scriptBuilder.ToString());

By changing the code, we can ensure all the validator scripts are being registered.

Posted in .Net, VS2008 | Tagged: , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 28 other followers