ASP.NET FAQ - Client Side Scripting

How can I add and remove an Html element dynamically using javascript?

Below is the javascript code which is used to add and remove div elements dynamically.Here the div tags are added in one base
div tag container.

<script>
	function AddHtmlElement()
	{
		var divElement = document.getElementById(’MYDIV’); 
		var divNumber= document.getElementById(’hiddenValue’); 
		var num = (document.getElementById(’hiddenValue’).value -1)+ 2; 
		divNumber.value = num; 
		var newdiv = document.createElement(’div’); 
		var divIdName = ’MYDIV’+num;
		newdiv.setAttribute(’id’,divIdName); 
		var divLoadedText=’Div ’+num+’ Is Added!’;	
		divElement.appendChild(newdiv);
		newdiv.innerHTML =divLoadedText+' '+'<a href=’#’ onclick=RemoveHtmlElement(’'+divIdName+'’)>Remove div ’'+divIdName+'’</a>';  
	}
	functionRemoveHtmlElement(divNum)
	{ 
		var divId = document.getElementById(’MYDIV’); 
		var childId = document.getElementById(divNum); 
		divId.removeChild(childId); 
	}
</script>

<form id='Form1' >
	<input id='hiddenValue' type='hidden' value='0'>
	<p>
		<a href='#' onclick='AddHtmlElement()'>Add Html Elements</a>
	</p>
	<div id='MYDIV'></div>
</form>
Permalink
How can users use ASP.NET’s server side methods to implement client scripts?

Here is an article from ftp online: Implement Client Scripts

Permalink
Is it possible to identify the source webpage where I came from?

You can identify the source webpage using the document.referrer command. The document object is the page currently loaded in the browser window – presumably your Web page. The referrer property is the page the visitor was at immediately prior to visiting the current page. You can code it as,

functionIdentifySourceWebPage()
{
	if(document.referrer != ’’) 
		document.write(’You came from ’ + document.referrer); 
}
Permalink
How can you do ClientSide Validation?

Client-side validation is enabled by default. If the client is capable, uplevel validation will be performed automatically. To disable client-side validation, set the page’s ClientTarget property to ‘Downlevel’ (‘Uplevel’ forces client-side validation). Alternatively, you can set an individual validator control’s EnableClientScript property to ‘false’ to disable client-side validation for that specific control.

<%@ Page ClientTarget=UpLevel %>
 
<html>
    <head>
        <script language="C#" runat=server>
 
            void Page_Load() 
            {
                if (!IsPostBack) 
                {
                                // Validate initially to force *s to appear before the first round-trip
                    Validate();
                }
            }
 
            void ValidateBtn_Click(Object Sender, EventArgs E) 
            {
                if (Page.IsValid == true) 
                {
                    lblOutput.Text = "Page is Valid!";
                }
                else
                {
                    lblOutput.Text = "Some of the required fields are empty";
                }
            }
 
        </script>
 
    </head>
    <body>
        <h3><font face="Verdana">Client-Side RequiredFieldValidator Sample</font></h3>
        <form runat="server">
            <table bgcolor="#eeeeee" cellpadding=10>
                <tr valign="top">
                    <td colspan=3>
                        <asp:Label ID="lblOutput" Name="lblOutput" Text="Fill in the required fields below"
                         ForeColor="red" Font-Names="Verdana" Font-Size="10" runat=server /><br>
                    </td>
                </tr>
                <tr>
                    <td colspan=3>
                        <font face=Verdana size=2><b>Credit Card Information</b></font>
                    </td>
                </tr>
                <tr>
                    <td align=right>
                        <font face=Verdana size=2>Card Type:</font>
                    </td>
                    <td>
                        <ASP:RadioButtonList id=RadioButtonList1 RepeatLayout="Flow"
                             onclick="ClientOnChange();" runat=server>
                            <asp:ListItem>MasterCard</asp:ListItem>
                                        <asp:ListItem>Visa</asp:ListItem>
                        </ASP:RadioButtonList>
                    </td>
                    <td align=middle rowspan=1>
                        <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server"
                            ControlToValidate="RadioButtonList1"
                            ErrorMessage="*"
                            Display="Static"
                            InitialValue=""
                            Width="100%">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td align=right>
                        <font face=Verdana size=2>Card Number:</font>
                    </td>
                    <td>
                                <ASP:TextBox id=TextBox1 onchange="ClientOnChange();" runat=server />
                    </td>
                    <td>
                        <asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server"
                            ControlToValidate="TextBox1"
                            ErrorMessage="*"
                            Display="Static"
                            Width="100%">
                        </asp:RequiredFieldValidator>
     
                    </td>
                </tr>
                <tr>
                    <td align=right>
                        <font face=Verdana size=2>Expiration Date:</font>
                    </td>
                    <td>
                        <ASP:DropDownList id=DropDownList1 onchange="ClientOnChange();"
                         runat=server>
                            <asp:ListItem></asp:ListItem>
                            <asp:ListItem >06/00</asp:ListItem>
                            <asp:ListItem >07/00</asp:ListItem>
                            <asp:ListItem >08/00</asp:ListItem>
                            <asp:ListItem >09/00</asp:ListItem>
                            <asp:ListItem >10/00</asp:ListItem>
                            <asp:ListItem >11/00</asp:ListItem>
                            <asp:ListItem >01/01</asp:ListItem>
                            <asp:ListItem >02/01</asp:ListItem>
                            <asp:ListItem >03/01</asp:ListItem>
                            <asp:ListItem <04/01</asp:ListItem>
                            <asp:ListItem <05/01</asp:ListItem>
                            <asp:ListItem <06/01</asp:ListItem>
                            <asp:ListItem <07/01</asp:ListItem>
                            <asp:ListItem <08/01</asp:ListItem>
                            <asp:ListItem <09/01</asp:ListItem>
                            <asp:ListItem <10/01</asp:ListItem>
                            <asp:ListItem <11/01</asp:ListItem>
                            <asp:ListItem <12/01</asp:ListItem>
                        </ASP:DropDownList>
                    </td>
                    <td>
                        <asp:RequiredFieldValidator id="RequiredFieldValidator3" runat="server"
                                    ControlToValidate="DropDownList1"
                            ErrorMessage="*"
                            Display="Static"
                            InitialValue=""
                            Width="100%">
                        </asp:RequiredFieldValidator>
                    </td>
                    <td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        <ASP:Button id=Button1 text="Validate" OnClick="ValidateBtn_Click"
                         runat="server" />
                    </td>
                    <td>
                    </td>
                </tr>
            </table>
        </form>
        <script language=javascript>
            <!--
            function ClientOnChange() 
            {
                if (typeof(Page_Validators) == "undefined")
                return;
                document.all["lblOutput"].innerText = Page_IsValid ? "Page is Valid!" : "Some of
                 the required fields are empty";
            }
            // -->
        </script>
    </body>
</html>
Permalink
Can I access the query string using JavaScript?

A query string is an optional part of a URL that goes after the file name and begins with a questionmark.

For eg the query string will be as

http://www.sitedemo/com/home.htm?newquerystringadded.

Here querystringvalue is the newquerystringadded.

The query string can be added and it can be retrieved as shown,

<div>
	<input type=button value='AddQueryString'  
	 onClick='self.location=
	self.location.protocol+’//’
	+self.location.host
	+self.location.pathname+’?addquerystring’'>
	
	<input type=button value='ShowQueryString' 
	onClick='alert(’Query string Value: ’+self.location.search)'>
</div>
Permalink
How can you make the text to scroll in the window’s status bar?

The text can be made to scroll using the javascript codings as below.

<html>
	<head>
		<title> Scrolling  Text On Window Status Bar </title>
		<script language='javascript'>
		// Scrolling Status Bar
		var delay = 60;
		var message = 'Syncfusion - .Net Essentials';
		message += ' Text Scrolling  In Window Status Bar';
		var spaceslength = 130;
		var spaces = '';
		for (var c = 0; c < spaceslength; c++)
		spaces += ' ';

		function init() 
		{
			timer = setTimeout(’scroll(130)’, 500);
		}

		function scroll(position) 
		{
			var startMessage = '';
			var cmd = '';

			if (position > spaceslength)
			{
				position--;
				cmd = 'scroll(' + position + ')';	
				timer = setTimeout(cmd, delay);
			}
			else if (position <= spaceslength && position > 0)
			{
				startMessage = spaces.substring(0, position);
				startMessage += message;
				position--;
				cmd = 'scroll(' + position + ')';
				window.status = startMessage;
				timer = setTimeout(cmd, delay);
			}
			else if (position <= 0)
			{
				 if (-position < message.length)
				 {
					startMessage += message.substring(-position, message.length);
				      	startMessage += spaces.substring(0, spaces.length / 4);
					startMessage += message;
					 position--;
					 cmd = 'scroll(' + position + ')';
					  window.status = startMessage;	
					  timer = setTimeout(cmd, delay*3);
				}
				else
				{
					cmd = 'scroll(' + spaces.length / 4 + ')';
					timer = setTimeout(cmd, delay);
			 	}
			}
		}
		</script>
	</head>
	<body bgcolor='#ffffff' onLoad='init()'>
		<blockquote>
			<h4>JavaScript  Demonstration- Scrolling  Text On Window Status Bar</h4>
		</blockquote>
	<hr/> 
	</body>
</html>
Permalink
How can I know if the client browser supports active scripting

You can detect and intercept the capabilities of your client using the namespace System.Web.HttpBrowserCapabilities :
VB.NET

Dim browser As System.Web.HttpBrowserCapabilities = Request.Browser
Response.Write('Support ActiveXControl: ' + browser.ActiveXControls.ToString())

C#

System.Web.HttpBrowserCapabilities browser = Request.Browser;
Response.Write ('Support ActiveXControl: ' + browser.ActiveXControls.ToString ());

For more details Refer: Detecting Browser Types in Web Forms

Permalink
How can I resize the window?

You can resize a window with JavaScript using ‘window.resizeTo(valueX,valueY)’.

<script> 
function ResizeWindow()
{
	window.resizeTo(800,800);
}	
</script>

Note also that the parameters of resizeTo() have different meaning in different browsers. In Internet Explorer the parameters specify the outer size of the window, while in Netscape Navigator they refer to the inner size (which does not include the window borders, toolbar, status bar, title bar, and the address line). The ‘window.resizeBy()’ method is slightly different than it’s ‘resizeTo()’ which changes the windows dimensions by number of pixels from it’s current size.

Permalink
How can you resize the html elements dynamically?

Html elements can be resized dynamically by using the style properties. In the below example the TextArea size is
increased dynamically on clicking the button.

<html>
	<script language=javascript>
		function resize()
		{
			document.form1.TextArea1.style.height=’600px’;
			document.form1.TextArea1.style.width=’400px’;
		}
	</script>
	<form name=form1>
		<TextArea  style='WIDTH: 200px; HEIGHT: 200px' name='TextArea1'></TextArea>
		<input type='button' style='WIDTH: 100px; HEIGHT: 100px' name='button1'> 
	</form>
	<input type=button value='ClickMe' onclick=javascript:resize()>
</html>
Permalink
How can you avoid postback on submit button?

The postback on submit button can be avoided by giving return=false in the event handler function as below.

<INPUT  type='submit' value='Submit' onclick='return false;'>
Permalink
How can you identify the drives available in the System?

The drives available in system can be identified using the following code.

<HTML> 
     <HEAD> 
	<SCRIPT language=JavaScript> 

		function ShowAvailableDrives() 
		{ 
			document.write(GetDriveList()); 
		} 

		function GetDriveList() 
		{ 
			var fso,  s,  n,  e,  x; 
			fso  = new ActiveXObject('Scripting.FileSystemObject'); 
			e  = new Enumerator(fso.Drives); 
			s  =  ''; 
			do 
		 	{	 
		   		x  =  e.item(); 
		   		s  =  s  +  x.DriveLetter; 
				s  +=  ':-    '; 
				if (x.DriveType  ==  3)     n  =  x.ShareName; 
				else if (x.IsReady)     n  =  x.VolumeName; 
				else      n  =  '[Drive not ready]'; 
				s  +=  n  +  '
'; 
				e.moveNext(); 
			}while (!e.atEnd()); 
  
		 	return(s); 
		}
		</SCRIPT>
	</HEAD>
	<BODY>
	    <P>
	      <SCRIPT language=JavaScript>  ShowAvailableDrives(); 
	    </P>
	</BODY>
</HTML>
Permalink
How can I check whether left or right mouse button has been clicked?

To determine whether the user clicked the left or right button, you can use the following properties.

  • Event.which in Netscape Navigator
  • event.button in Internet Explorer

If the value of these properties is 1, the event occurred for the left button. In the following example, the onMouseDown event handler displays the messages Left button or Right button, depending on the mouse button you actually have clicked. The messages will appear on your browser’s status bar. Click or right-click anywhere on this page to see it work:

<html>
     <head>
		<script language='JavaScript'>
		<!--
		function mouseDown(e) 
		{
			 if (parseInt(navigator.appVersion)>3)
			 {
				var clickType=1;
			  	if (navigator.appName=='Netscape') clickType=e.which;
				else clickType=event.button;
				if (clickType==1) 
  				{
					self.status=’Left button!’;
					alert('Left Button');
			 	}
			                if (clickType!=1)
  			 	{
			  		self.status=’Right button!’;
					alert('Right Button');
				}	
			}
		 return true;
		}
		if (parseInt(navigator.appVersion)>3)
		{
			 document.onmousedown = mouseDown;
			 if (navigator.appName=='Netscape') 
			  document.captureEvents(Event.MOUSEDOWN);
		}
		//-->
		</script>
	</head>
</html>
Permalink
How can we check whether a function exists in javascript?

We can check the existence of a function by Window.FunctionName as shown below, where the FunctionName is the name of the function,whose existence has to be checked.

<SCRIPT LANGUAGE='JavaScript' type='text/javascript'>
functionCheckIfExists()
{
	alert(’FunctionExists’)
}
if( window.CheckIfExists)
{
 	CheckIfExists()
}
else
{
 	alert( Function Not Exists!’ )
}
</SCRIPT>
Permalink
How can i resize the dialog window?

You can size a window with JavaScript using ‘window.resizeTo(valueX,valueY)’.

<script>
functionResizeWindow()
{
	window.resizeTo(800,800);
}	
</script>

Note also that the parameters of resizeTo() have different meaning in different browsers: in Internet Explorer the parameters specify the outer size of the window, while in Netscape Navigator they refer to the inner size (which does not include the window borders, toolbar, status bar, title bar, and the address line). The ‘window.resizeBy()’ method is slightly different than it’s ‘resizeTo()’ which changes window’s dimensions to a certain number of pixels from it’s current size.

Permalink
How can you get the X Co-ordinates Y Co-ordinates values during the Mouse Movement?

The X and y co-ordinates during the mouse movement can be obtained by the following codings.

<html>
	<body>
		<form name='Show'>
			<b>X Co-Ordinate Value:</b><input type="text" name="X" value="0" size="4"> <br>
                        <b>Y Co-Ordinate Value:</b><input type="text" name="Y" value="0" size="4"> <br>
		</form>
		<script language='Javascript'>
		<!--

			// Detect if the browser is IE or not.
			// If the browser is not IE, we assume that the browser is NS.
			var IE = document.all?true:false

			// If NetScape then set up for mouse capture
			if (!IE) document.captureEvents(Event.MOUSEMOVE)

			// Set-up to use getMouseXY function onMouseMove
			document.onmousemove = getMouseXY;

			// Temporary variables to hold mouse x-y pos.s
			var tempX = 0
			var tempY = 0

			// Main function to retrieve mouse x-y pos.s

			function getMouseXY(e) 
			{
  				if (IE) { // grab the x-y pos.s if browser is IE
				tempX = event.clientX + document.body.scrollLeft;
				tempY = event.clientY + document.body.scrollTop;
			}
			else
			{
				  // grab the x-y pos.s if browser is NS
		  		  tempX = e.pageX;
   				  tempY = e.pageY;
  			}  
			// catch possible negative values in NS4
			if (tempX < 0){tempX = 0}
			if (tempY < 0){tempY = 0}  

			// show the position values in the form named Show
			// in the text fields named MouseX and MouseY
			document.Show.X.value = tempX;
			document.Show.Y.value = tempY;
			return true;
		}
		//-->
		</script>
	</body>
</html>
Permalink
How can you make a piece of text get moving along the mouse Movement?

We can make text to move along the mouse using javascript as given below,

<html>
	<head>
		<style>
			.spanstyle
			 {
				position:absolute;
				visibility:visible;
				top:-50px;
				font-size:10pt;
				font-family:Verdana;
 			            	font-weight:bold;
				color:black;
			}
		</style>
		<script>
			var x,y
			var step=20
			var flag=0
			var text='Syncfusion .NET Essentials '
			text=text.split('')
			var xpos=new Array()
			for (i=0;i<=text.length-1;i++) 
			{
				xpos[i]=-50
			}
			var ypos=new Array()
			for (i=0;i<=text.length-1;i++) 
			{
				ypos[i]=-50
			}

			function handlerMM(e)
			{
				x = (document.layers) ? e.pageX : document.body.scrollLeft+event.clientX
				y = (document.layers) ? e.pageY : document.body.scrollTop+event.clientY
				flag=1
			}

			function MoveText() 
			{
				if (flag==1 && document.all) 
				{
			    		for (i=text.length-1; i>=1; i--) 
					{
		   				xpos[i]=xpos[i-1]+step
						ypos[i]=ypos[i-1]
				    	}
					xpos[0]=x+step
					ypos[0]=y
					for (i=0; i<text.length-1; i++) 
					{
						var spanvalue=eval('span'+(i)+'.style')
						spanvalue.posLeft=xpos[i]
						spanvalue.posTop=ypos[i]
					}
				}
				else if (flag==1 && document.layers) 
				{
					for (i=text.length-1; i>=1; i--) 
					{
	   					xpos[i]=xpos[i-1]+step
						ypos[i]=ypos[i-1]
				    	}
					xpos[0]=x+step
					ypos[0]=y
					for (i=0; i<text.length-1; i++) 
					{
						var spanvalue=eval('document.span'+i)
						spanvalue.left=xpos[i]
						spanvalue.top=ypos[i]
					}
				}
				var timer=setTimeout('MoveText()',30)
			}
		</script>
	</head>
	<body onload="MoveText()" style="width:100%;overflow-x:hidden;overflow-y:scroll">
		<script>
			for (i=0;i<=text.length-1;i++) 
			{
				document.write("<span id='span"+i+"' class='spanstyle'>")
				document.write(text[i])
				document.write('</span>')
			}
			if (document.layers)
			{
				document.captureEvents(Event.MOUSEMOVE);
			}
			document.onmousemove = handlerMM;
		</script>
	</body>
</html>
Permalink
How can the a client side function be called on a button click event?

In 2.0 Button control has a property OnClientClick which is used to call a client side function before postback.

<asp:Button ID='Button1' runat='server' Text='Button'  OnClientClick='ClientFunction()'/>
<script>
	functionClientFunction()
	{
		alert('ClientFunctionCalled');
	}
</script>
Permalink
How can you generate a clock in javascript?

A clock can be generated using the javascript function as given below.

<html>
<head>
<script language='JavaScript'>

function startclock()
{
	var thetime=new Date();
	var nhours=thetime.getHours();
	var nmins=thetime.getMinutes();
	var nsecn=thetime.getSeconds();
	var nday=thetime.getDay();
	var nmonth=thetime.getMonth();
	var ntoday=thetime.getDate();
	var nyear=thetime.getYear();
	var AorP=' ';
	if (nhours>=12)
    		AorP='P.M.';
	else
    		AorP='A.M.';
	if (nhours>=13)
   		 nhours-=12;
	if (nhours==0)
   		nhours=12;
	if (nsecn<10)
 		nsecn='0'+nsecn;
	if (nmins<10)
 		nmins='0'+nmins;
	if (nday==0)
  		nday='Sunday';
	if (nday==1)
		nday='Monday';
	if (nday==2)
  		nday='Tuesday';
	if (nday==3)
  		nday='Wednesday';
	if (nday==4)
  		nday='Thursday';
	if (nday==5)
  		nday='Friday';
	if (nday==6)
  		nday='Saturday';
	nmonth+=1;	
	if (nyear<=99)
  		nyear= '19'+nyear;
	if ((nyear>99) && (nyear<2000))
		nyear+=1900;
	document.clockform.clockspot.value=nhours+': '+nmins+': '+nsecn+' '+AorP+' '+nday+', '+nmonth+'/'+ntoday+'/'+nyear;
	setTimeout(’startclock()’,1000);
} 

</script>
</head>

<body>

<form name='clockform'>
Current Time: <INPUT TYPE='text' name='clockspot' size='40'>
</form>
<script language='JavaScript'>

startclock();

</script>

</body>
</html>
Permalink
How can I use a Timer Control to refresh a page automatically at a specified interval
<asp:DropDownList id='DropDownList1' runat='server' onChange='SetClientRefresh(this);'>
	<asp:ListItem Value='1000'>1 second</asp:ListItem>
	<asp:ListItem Value='2000'>2 seconds</asp:ListItem>
	<asp:ListItem Value='3000'>3 seconds</asp:ListItem>
</asp:DropDownList>
<script language=’javascript’>
var cTimeOut = null;
function SetClientRefresh(sel)
{
	var newRefresh = sel.options[sel.selectedIndex].value;
	if (cTimeOut != null)
	{
		window.clearTimeout(cTimeOut);
	}
	cTimeOut = window.setTimeout('ReLoadPage()', newRefresh);
}

function ReLoadPage()
{
	window.location.reload();
}
</script>
Permalink
How to pop up a message box when no item in the dropdownlist is selected before postback?
  • Make sure to add a ListItem with Text=’Please Choose’ and Value =”.
  • Add a RequiredFieldValidator with ControlToValidate= <Dropdownlist1> and Display=’Dynamic’
  • Add a ValidationSummary with ShowMessageBox =true
<asp:DropDownList id='DropDownList1' runat='server'>
	<asp:ListItem Value=''>Please Choose</asp:ListItem>
	<asp:ListItem Value='Faq'>Faq</asp:ListItem>
	<asp:ListItem Value='Tips'>Tips</asp:ListItem>
	<asp:ListItem Value='Tricks'>Tricks</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator id='RequiredFieldValidator1' style='Z-INDEX: 102; LEFT: 176px; POSITION: absolute; TOP: 48px'
	runat='server' ErrorMessage='Please Select an Item in the dropdownlist' ControlToValidate='DropDownList1'
	Display='Dynamic'></asp:RequiredFieldValidator>
<asp:Button id='Button1' style='Z-INDEX: 104; LEFT: 128px; POSITION: absolute; TOP: 16px' runat='server'
	Text='Button'></asp:Button>
<asp:ValidationSummary id='ValidationSummary1' style='Z-INDEX: 105; LEFT: 176px; POSITION: absolute; TOP: 72px'
	runat='server' ShowMessageBox='True' ShowSummary='False'></asp:ValidationSummary>
Permalink
How can I make a Textbox a mandatory field if a checkbox is checked on a button click event in the client side?
<asp:TextBox id='TextBox1' style='Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 104px' runat='server'></asp:TextBox>
<asp:CheckBox id='CheckBox1' style='Z-INDEX: 102; LEFT: 24px; POSITION: absolute; TOP: 80px' runat='server'></asp:CheckBox>
<asp:Button id='Button1' style='Z-INDEX: 103; LEFT: 32px; POSITION: absolute; TOP: 144px' runat='server' Text='Button'></asp:Button>
<script>
function func1()
{
	 if(document.getElementById ('CheckBox1').checked == true) 
	{ 
 		if(document.getElementById('TextBox1').value == '') 
		{ 
			alert('Enter something in textbox');
		 } 
	}
   
 }
</script>

VB.NET

Button1.Attributes.Add ('onclick' , 'return func1()');

C#

Button1.Attributes.Add ('onclick' , 'return func1()');
Permalink
How to disable a Dropdownlist once someone has selected an item in the Dropdownlist
<asp:DropDownList id='DropDownList1' runat='server'>
	<asp:ListItem Value='Red'>Red</asp:ListItem>
	<asp:ListItem Value='Blue'>Blue</asp:ListItem>
	<asp:ListItem Value='Green'>Green</asp:ListItem>
</asp:DropDownList>

VB.NET

DropDownList1.Attributes.Add('onChange','this.disabled=true;' )

C#

DropDownList1.Attributes.Add('onChange','this.disabled=true;' );
Permalink
How to change the BackgroundColor of a page based on the value selected in a DropdownList
<asp:DropDownList id='DropDownList1' runat='server' AutoPostBack='True'>
	<asp:ListItem Value='Red'>Red</asp:ListItem>
	<asp:ListItem Value='Blue'>Blue</asp:ListItem>
	<asp:ListItem Value='Green'>Green</asp:ListItem>
</asp:DropDownList>

VB.NET

Page.RegisterClientScriptBlock('BodyStyle', '<style type=’text/css’>body{background-color: ' + DropDownList1.SelectedItem.Value + ';}</style>')

C#

Page.RegisterClientScriptBlock('BodyStyle', '<style type=’text/css’>body{background-color: ' + DropDownList1.SelectedItem.Value + ';}</style>');
Permalink
How to display a message in the status bar of a browser window
<body  onload ='window.status=’First Page’'>
..
</body>
Permalink
How to rotate a Label Text
<asp:Label id='Label1' style='writing-mode:tb-rl' runat='server'>Label</asp:Label>
Permalink
How to check/ uncheck a checkbox based on the text entered in textbox
<asp:CheckBox id='CheckBox1' runat='server'></asp:CheckBox>
<asp:TextBox id='TextBox1' runat='server'></asp:TextBox>
<script type='text/javascript'>
function chkTextEntered()
{
	document.getElementById('CheckBox1').checked = true;
        	if(document.getElementById('TextBox1').value =='' )
    	{
		document.getElementById('CheckBox1').checked = false;
	}
}
</script>

In Page_Load
VB.NET

TextBox1.Attributes.Add('onKeyDown', 'chkTextEntered();')

C#

TextBox1.Attributes.Add('onKeyDown', 'chkTextEntered();');
Permalink
How to disable the right click option on a web page
<body oncontextmenu='return false;'>
...
</body>

Note :User can still do a View/Source in their browser menu.

Permalink
How to resize two <div> tags on a webform
<script>
function ResizeDivs() 
{ 
var DivTop = document.getElementById(’Top’) 
var DivBottom = document.getElementById(’Bottom’) 
var BodyHeight = 0; 

var DivTopHeight = 0; 
var DivBottomHeight = 0; 
var DivBottomPosition = 0; 

BodyHeight = document.body.clientHeight; 
DivBottomHeight = DivBottom.clientHeight; 
DivBottom.style.top = BodyHeight - DivBottomHeight; 
DivTop.style.height = DivBottom.style.top; 

} 

window.onload = ResizeDivs; 
window.onresize = ResizeDivs;</script>
<div id='Top' style='position:absolute; top:0px; left:0px; background-color:#c0c0c0; overflow:auto; width:100%'>
Top Div Text: 

Syncfusion  

Sample code 

To  

autosize 

<div> 

tag 
 
</div>
<div id='Bottom' style='position:absolute; background-color:#808080; width:100%'>
Bottom Div Text: 

 Footer for the page 

 Line1 

 Line2
</div>

Note : if the DIV has no borders, clientHeight works. If you are going to be using a border or margins, then use offsetHeight

Permalink
How to hide a control using javascript
document.getElementById('<id>').style.visibility='hidden';
Permalink
How to emit client-side javascript blocks from VB.NET/C#

The RegisterStartupScript method emits the script just before the closing tag of the Page object’s <form runat= server> element.

VB.NET

RegisterStartupScript('Sample', '<SCRIPT Language=’javascript’>alert(’Hello World’);</SCRIPT>')

C#

RegisterStartupScript('Sample', '<SCRIPT Language=’javascript’>alert(’Hello World’);</SCRIPT>');

Alternatively, use the RegisterClientScriptBlock method which emits the client-side script just after the opening tag of the Page object’s <form runat= server> element.

Permalink
How can the ‘Enter’ key be disabled?

In order to avoid the Form Submission by pressing the ’Enter Key’ you have to write following code on the KeyPress Event Of the Body Tag

function DisableEnterKey()
{
     if (window.event.keyCode == 13) 
    {
        event.returnValue=false; 
                    event.cancel = true;
    }
}
 
<body onkeydown="DisableEnterKey();">
Permalink
Is there Trim function available in Javascript?

There is no predefined trim function available. The function written below is used to Trim white spaces.

//Trim Function
function LTrim(str)
{
	var whitespace = new String(' \t\n\r');
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1)
	{
		var j=0, i = s.length;
	 	while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
		j++;
		s = s.substring(j, i);
    	}
	return s;
}

function RTrim(str)
{
	var whitespace = new String(' \t\n\r');
	var s = new String(str);
	 if (whitespace.indexOf(s.charAt(s.length-1)) != -1) 
	 {
		var i = s.length - 1;      
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
		i--;
		s = s.substring(0, i+1);
	 }
	 return s;
}

function Trim(str)
{
	return RTrim(LTrim(str));
}
Permalink
How can we check whether the cookie is enabled?

It can be done by checking the read only property navigator.cookieEnabled. navigator.cookieEnabled will give the value true/false based on the browser support for cookies.

functionCookieEnabled() 
{ 
	if(navigator.cookieEnabled)
	{
		alert('Cookie Enabled');
	}
}
Permalink
How the browser name can be detected?

We can use navigator.appName property, to identify the browser we are using .For Netscape browsers, the value of navigator.appName is ‘Netscape’. For Microsoft Internet Explorer browsers,the value of navigator.appName is ‘Microsoft Internet Explorer’ .

The following code is used for browser detection.

function BrowserDetect()
{

                document.write(’navigator.appName = ’+navigator.appName+’
’)
	document.write(’navigator.userAgent = ’+navigator.userAgent+’
’)

	if ((navigator.userAgent).indexOf('Opera')!=-1)
	{
 		document.write('You are using an Opera browser.')
	}
	else if (navigator.appName=='Netscape') 
	{
 		document.write('You are using a Netscape browser.')
	}
	else if ((navigator.appName).indexOf('Microsoft')!=-1) 
	{
		 document.write('You are using Microsoft Internet Explorer.')
	}
}
Permalink
How can i form a regular expression which identifies a valid whole number without decimal places?

The regular expression used to identify only the numbers is var regexp = /\D|\./.

<script> 
function IdentifyNumbers() 
{ 
	var Number = document.getElementById('NumericValue').value; 
	var regexp = /\D|\./ ; 
	if(Number.match(regexp)) 
	{
		alert('Only enter numbers and no decimal point\nInvalid input: '+Number.match(regexp));
	} 
	else
	{
		alert('Valid Input');
	}
} 
</script>
Permalink
How to parse the files/folders in the client’s file system?

Here is a technique usable in IE Only

	var fso=new ActiveXObject('Scripting.FileSystemObject');
	function ShowFilesIn(path) // path could be 'C:\Test' for example.
	{
		if(fso.FolderExists(path))
		{
			ShowFiles(fso.GetFolder(path)); 
		}  
	}

	function ShowFiles(folderpath)
	{
		var objFso = new Enumerator(folderpath.Files);
		for(i=0;!objFso.atEnd();objFso.moveNext())
		{
			alert(objFso.item().name);
		}
	}
Permalink
How to create files on the client m/c using JavaScript?

Here is a technique usable in IE Only.

	var fso=new ActiveXObject('Scripting.FileSystemObject');
	function WriteToFile()
	{
		var writeStream=fso.CreateTextFile('C:\TestFile.txt',true);
		writeStream.writeLine('This is a test file');
		writeStream.close();
	}
Permalink
How to show Modal and Modeless dialog windows in Javascript?

When you show a modal dialog the window remains on top of other windows until the user explicitly closes it.

window.showModalDialog('Test.html','dialogWidth:400px; dialogHeight:225px; status:no; center:yes');

When you show a modeless dialog the window remains on top of other windows, but you can still access the other windows.

window.showModelessDialog('Test.html','dialogWidth:400px; dialogHeight:225px; status:no; center:yes');
Permalink
Are there any resources regarding the Mozilla specific Browser Objects and CSS information

Official Gecko DOM Reference:
Gecko Dom Reference

Here is a very useful list of custom CSS styles specific to Mozilla:
XUL Planet

Permalink
Why does the SmartNavigation does not work on the live server but works perfectly on the Development Machine

May be the domain does not have access to the aspnet_client folder which is located in the wwwroot folder. i.e the website is not able to find the scripts for smart navigation. So set up a virtual folder to the wwwroot/aspnet_client and it will fix the problem.

Permalink
How to create dynamic javascripts in server side code based on server side variables?

Here’s and example:

VB.NET

Dim value As String = 'pic1.jpg'
Button1.Attributes('onMouseOver') = 'alert( ’' + value + '’);'

C#

string value = 'pic1.jpg'; 
Button1.Attributes['onMouseOver'] = 'alert( \'' + value + '\');' ;
Permalink
How to get the confirmation of Yes/No from a javascript pop-up and display the value on the page

Code Behind

Button1.Attributes.Add('onclick', 'getMessage()')

Client Side

<SCRIPT language=javascript>
function getMessage() 
{ 
var ans; 
ans=window.confirm(’Is it your confirmation.....?’); 

if (ans==true) 
	{ 
		document.Form1.hdnbox.value=’Yes’; 
	} 
else 
	{ 
		document.Form1.hdnbox.value=’No’;} 
	} 
</SCRIPT>

To display the Yes/No value selected by user, in your code behind file:

Response.Write(Request.Form('hdnbox'))
Permalink
Why can’t I open a new browser window from within server code?

Server code executes on Server, whereas the new window is created on the client. You need to use client-side script to open new window.

Permalink
How to set the background color of a web page using code behind?

Yes

  1. In the body tag, add runat=’server’ and give the tag an id (e.g. id=’bodyID’).

  2. In the class definition in the code-behind, add
    VB.NET

    Protected bodyID As System.Web.UI.HtmlControls.HtmlGenericControl
    

    C#

    protected  System.Web.UI.HtmlControls.HtmlGenericControl bodyID  ;
    
  3. In code, use the attributes collection to set the bgcolor attribute:
    VB.NET

    bodyID.Attributes.Add('bgcolor', 'green')
    

    C#

    bodyID.Attributes.Add('bgcolor', 'green');
    
Permalink
How to determine if the Browser supports javascript?

VB.NET

if Page.Request.Browser.JavaScript then
...
else
...
end if

C#

if (Page.Request.Browser.JavaScript )
{
...
}
else
{
...
}
Permalink
How can I change the scroll bar color

Use Style Sheet to change the color of scroll-bar

body 
{
    FONT-SIZE: 8pt;
    COLOR: #000000;
    background-color: #EEEEEE; 
    scrollbar-face-color: #EEEE99;
    scrollbar-highlight-color: #DDDDDD;
    scrollbar-shadow-color: #DEE3E7;
    scrollbar-3dlight-color: #FF6600;
    scrollbar-arrow-color:  #006699;
    scrollbar-track-color: #EFEFEF;
    scrollbar-darkshadow-color: #98AAB1;
}
Permalink
How to change a Label element’s text in javascript
document.getElementById('Label1').innerText = 'Changed Text';
Permalink
Can I modify WebUIValidation.js

Extract from MSDN :

You are encouraged to read the script to see more of what is going on. However, it is not recommended that you modify these scripts, because their function is very closely tied to a particular version of the run time. If the run time is updated, the scripts may need a corresponding update, and you will have to either lose your changes or face problems with the scripts not working. If you must change the scripts for a particular project, take a copy of the files and point your project to them by overriding the location of the files with a private web.config file.It is perfectly fine to change this location to be a relative or absolute reference.

For more details refer ASP.NET Validation in Depth

Permalink
Does JavaScript support hashtables/ hash tables or dictionary type data structures?

All Objects in JavaScript implicitly support hash table like syntax by virtue of behaving as Associative Arrays. Properties of an object can be accessed in 2 ways as shown below:

object.property = value;
object['property'] = value;

So, when used in a hash table like syntax as shown above, you will be simply creating dynamic properties and assigning values to those properties.

Permalink
How to open a new window without IE menus and toolbars on click of a button

VB.NET

Button2 .Attributes.Add ('onclick', 'window.open(’webform1.aspx’,’_blank’,’toolbar=no’)')

C#

Button2 .Attributes.Add ('onclick', 'window.open(’webform1.aspx’,’_blank’,’toolbar=no’)');
Permalink
How to open a browser window with maximum size on click of a button

VB.NET

Button1.Attributes.Add('onclick', 'window.open(’page2.aspx’,’’,’fullscreen=yes’)')

C#

Button1.Attributes.Add('onclick', 'window.open(’page2.aspx’,’’,’fullscreen=yes’)');
Permalink
How to open a new Window using javascript function from a Link button

VB.NET

link.Attributes( 'onClick' ) = 'window.open( ’url’, ’name’, ’properties’ )';

C#

link.Attributes[ 'onClick' ] = 'window.open( ’url’, ’name’, ’properties’ )';

You can also check out Andy Smith’s RemoteWindow Control

Permalink