Adding Java Script to the SharePoint WebPart

There are two ways, you can place a javascript in your webpart.

Scenario –1

Let’s consider, you have a javascript file with some javascript functions. You want to call one of the client side functions inside the webpart code. Here goes the solution

Java script File
----------------------------------------------------------------------
function do_confirmService(ID)
{
var textbox = document.GetElementByID(ID);
alert(textbox.value);
}
------------------------------------------------------------------------------
Code

Place the javascript file in Layouts folder and register it on PreRender function. Code in the webpart file goes here
------------------------------------------------------------------------------------

------------------------------------------------------------------------------------
Complete Path of the Layout folder is %Program Files%/Common Files/web server extensions/12/Template/Layouts

2.Call the javascript function in Client event. Code goes here
----------------------------------------------------------------------------------------
protected override void CreateChildControls()

{
TextBox sample = new TextBox();
sample.ID = "sampletextbox";

Button testButton = new Button();
testButton.Text = "click me";
testButton.Attributes.Add("OnClick", "javascript:doConfirmService(" + this.ClientID + "_sampletextbox");

this.Controls.Add(sample);
this.Controls.Add(testButton);
}
--------------------------------------------------------------------------------------
Now deploy the webpart.Enter some text in the textbox and click the button.It will alert the textbox value you entered.

Scenario –2

Suppose you don’t want to go for the javascript file and want to place the javascript in the code itself ,then here is the solution

///
/// Method Name : OnPreRender
/// Description : This method is for registering JavaScript file
///

/// EventArgs

protected override void OnPreRender(EventArgs e)
{
string script= @" function do_confirmService(ID)
{
var textbox = document.GetElementByID(ID);
alert(textbox.value);
}”

//regestering the Javascript
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Javascriptkey", script);
base.OnPreRender(e);

}

Then call this javascript function on the button click as discussed in step 2 above.