Thursday, March 13, 2008

JavaScript usage in Web Part


If you want to use JavaScript in your Web part then you have two options:


1) Refer to some external JavaScript file.



ClientScriptManager cs = Page.ClientScript;
// Include the required javascript file.
if (!cs.IsClientScriptIncludeRegistered("tab_javascript"))
cs.RegisterClientScriptInclude(this.GetType(), "tab_javascript",
"/_layouts/BCLBlast/tab.js");


I placed the JavaScript file at following location:


C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\BCLBlast







2) Write JavaScript in Web Part file.



// Initialize javascript variables to have list of all tabs and headers
if (!cs.IsClientScriptBlockRegistered("tabs_list"))
{
string tabVariables =
@"<script type=""text/javascript"">" +Environment.NewLine +
@"var tabs = [{0}] ;" + Environment.NewLine +
@"var tabheaders = [{1}] ;"+Environment.NewLine+
@"var _currentTab = null ;" + Environment.NewLine +
@"</script>";

string tabPages = "", tabHeaders = "";
for (int i = 0; i < SearchInformationSources.TotalSearchProviders; i++)
{
tabPages += "\"tab" + i.ToString() + "\", ";
tabHeaders += "\"tabheader" + i.ToString() + "\", ";
}

if (tabHeaders.Length > 1)
{
tabPages = tabPages.Remove(tabPages.Length - 2, 2);
tabHeaders = tabHeaders.Remove(tabHeaders.Length - 2, 2);
}

cs.RegisterClientScriptBlock(GetType(), "tabs_list",
String.Format(tabVariables, tabPages, tabHeaders));
}



Whole code snippet is as follows:





protected override void OnPreRender(EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
//Include the required javascript file.
if (!cs.IsClientScriptIncludeRegistered("tab_javascript"))
cs.RegisterClientScriptInclude(this.GetType(),
"tab_javascript", "/_layouts/BCLBlast/tab.js");


// Initialize javascript variables to have list of all tabs and headers
if (!cs.IsClientScriptBlockRegistered("tabs_list"))
{
string tabVariables =
@"<script type=""text/javascript"">" + Environment.NewLine +
@"var tabs = [{0}] ;" + Environment.NewLine +
@"var tabheaders = [{1}] ;" + Environment.NewLine +
@"var _currentTab = null ;" + Environment.NewLine +
@"</script>";

string tabPages = "", tabHeaders = "";
for (int i = 0; i < SearchInformationSources.TotalSearchProviders; i++)
{
tabPages += "\"tab" + i.ToString() + "\", ";
tabHeaders += "\"tabheader" + i.ToString() + "\", ";
}

if (tabHeaders.Length > 1)
{
tabPages = tabPages.Remove(tabPages.Length - 2, 2);
tabHeaders = tabHeaders.Remove(tabHeaders.Length - 2, 2);
}

cs.RegisterClientScriptBlock(GetType(), "tabs_list",
String.Format(tabVariables, tabPages, tabHeaders));
}
}




Here you to have to implement the OnPreRender method to write the JavaScript code.

12 comments:

Grace83f said...

Hi Avinash,

Thanks for the post. It really help me on how to include javascript file into web part.

But, May I ask the location to put the external javascript file? You did say to put in "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\BCLBlast", but i cannot find this "BCLBlast" folder. Is it self-created folder? May I know more details about where to upload the javascript file?

Thank you. Really appreciate it.

Grace83f

Avinash said...
This comment has been removed by the author.
Avinash said...

Yes you are right BCLBlast is self-created folder. You can place it at your anywhere you like.

Grace83f said...

Hi Avinash,

Thank you so much for your fast reply. Really appreciate it.

I haved followed your steps to include external file, but still cannot work.

I had placed the javascript file under "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\BCLBlast" folder.

This is how I include the javascript file in webpart code:
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsClientScriptIncludeRegistered("calendar_javascript"))
{
cs.RegisterClientScriptInclude(this.GetType(), "calendar_javascript", "/_layouts/BCLBlast/Scripts/test.js");
}

Here is the code i placed to call the function in javascript:
calendarImgBtn.OnClientClick = "alertMe('SUCCESSFUL');return false;";

The javascript file I placed(named "test.js") is just a simple javascript. I just do for simple test first. Here it is:
alertMe(txt)
{
alert(txt);
}

May I have your advice? Did I do correctly? I am pretty new in this sharepoint. Thanks in advanced.


Grace83f

Grace83f said...

Hi Avinash,

Can WORK already :)

There are 2 problems in the code.
*First, is my javascript syntax error. Forgotten to put 'function' on the function name
*Second, is because the folder name of javascript i tried to call.
should be "/_layouts/BCLBlast/test.js", instead of "/_layouts/BCLBlast/Scripts/test.js"

Thanks for the help. Have a nice day!


Grace83f

Grace83f said...

Hi Avinash,

Can I have your advice?

I am using System.Web.UI.WebControls.ImageButton and System.Web.UI.WebControls.TextBox for the webpart. The scenario is when the ImageButton is clicked, it will call javascript to update the TextBox value.

If we are using normal textbox from the form tag, we can just use document.getElementById('id').value to update the textbox value. But, how if we are using System.Web.UI.WebControls.TextBox? Do you have any idea?

Thank you in advanced.


Grace83f

Avi said...

Hi Grace,

If u want to access the Server side TextBox from javascripts then first u have get the clientId of server control and then u can change its value.

<asp:TextBox ID="textBox1" Wrap="true" TextMode="MultiLine" runat="server" Width="215px"></asp:TextBox>

<script type="text/javascript">
var txtID = '<%= textBox1.ClientID %>';

document.getElementById(txtID).innerText = '';
</script>


~Avi

Huradi Praveen Kumar said...

Hi avinash am hyderabad,
i have small problem...hope u will provide me solution...
i want make use of Ajax controls in Sharepoint2007...
the problem is that i mainly use web user controls(i.e ascx files)
after writing the code i will place the web user controls in Controltemplate folder of Sharepoint.deploy that web user control to Sharepoint site.
my user control is contains ajax control..but i cant see ajax control in sharepoint site....
please help me out...
wat i hav done
1)i configured the web config file
2)i hav implemend ajax in ascx web user control
how to display ths control in my sharepoint site

huradipraveen@gmail.com

Avinash said...

Hi Praveen,

1) First test whether you are able to run the ASCX in your application or not.

For that, place your ASCX (both .cs and .ascx) files at one of the following locations (instead of ControlTemplate for simplicity):

a) C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\

b) C:\Inetpub\wwwroot\wss\VirtualDirectories\[port-number]\

2) Then consume the above created ASCX in your SharePoint page, either directly or via webpart.

a) In case of direct access, use it like normal ASCX by providing the control src, tagname and tagprefix.

b) In case of via webpart refer Developing and Using Web User Control in Web Parts in MOSS 2007


3) If you are able to run usercontrol (ASCX) properly, then proceed to implement AJAX functionality in it. For this please refer

AJAX in SharePoint 2007


4) Now if you are able to run properly both ASCX and AJAX, then move your files to controltemplate. Refer the usage Welcome.ascx file (C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES\Welcome.ascx). Welcome.ascx is used in the Master page of your site.


~ Avinash

Unknown said...

Hi Avinash,

I have created a webpart using C#, in Visual studio 2008 which has 4 text boxes.
I have also place one total text box.
I want to call java script function to display total in the total text box when user enter values in text boxex one by one.
Can you please help me, how could i initiate the javascript function as i am creating the text boxes dynamically in method: protected override void CreateChildControls()

Avinash said...

Hi Abhijit,
Once you created all TextBoxes dynamically, write a JavaScript function that accept two parameters (Sender TextBox's Client ID and Total TextBox's Client ID):

function Add(textBox1ClientID, totalBoxClientID)
{
//use document.GetElementByID to get instances of both textboxes
//perform ur normal operation
}

Register above JS function to ur Textboxes in CreateChildControl method itself....
textbox1.Attribute.Add("OnLostFocus", "JavaScript:Add(textbox1.ClientID, TotalTextbox.ClientID);

//Check exact syntax in above code


Now register all JS code using RegisterClientScript in CreateChildControl method.

Anonymous said...

Hi Avinash, i m working on sharepoint webpart and i have a textbox in my webpart where the user will enter a date i m trying to add a calender popup next to the textbox so the user can select the date from the caleder to the textbox...can you please send me sample code how can i achieve this.

Google