Live Chat Icon For mobile
Live Chat Icon

ASP.NET FAQ

Find answers for the most frequently asked questions
Expand All Collapse All

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

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

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

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

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

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

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

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

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

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

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

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

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

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]" }="" 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('')
			}
			if (document.layers)
			{
				document.captureEvents(Event.MOUSEMOVE);
			}
			document.onmousemove = handlerMM;
		</script>
	</body>
</html>
</text.length-1;></text.length-1;>
Permalink

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

<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
  • 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

<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

<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

<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

<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

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

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

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

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

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

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

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

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

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

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

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

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

Share with

Share on twitter
Share on facebook
Share on linkedin

Couldn't find the FAQs you're looking for?

Please submit your question and answer.