Wednesday, October 1, 2008

JavaScripts Tips n Tricks

1) ClientID usage :

If you want to access the a Server side TextBox / Control written in ASP.Net from JavaScript code, then first you have get the clientID of that server control and then you can change access it.



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



Note: If an external JavaScript file is referenced in ASPX page, then ASP.NET won't be preprocessing it for server tags (<%...%>), as it isn't part of a ASPX file. You probably need to include the JavaScript code directly in the ASPX file (inline JavaScript code), or set up a global variable in there that is accessed by the JS file when it needs the clientID.



2) String to Number conversion :


var num = Number("11");




3) Case-Insensitive search :


//To make case-insensitive search, used SEARCH instead of INDEXOF.
var sampleString = 'Search case-insensitive based on InputString';
var index = sampleString.search(/InputString/i);




4) unescape() function :


//The unescape() function decodes a string encoded with escape().
var sURL = unescape(window.location.href);


Reference:
JavaScript unescape() Function



5) Trim string :


str = str.replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');




6) Encode string :


str = encodeURIComponent(str);




8) Date Validation :



function isValidDate(strNewDate)
{
var newDate = new Date(strNewDate);

if (newDate.toString() == "NaN" || newDate.toString() == "Invalid Date")
return false;
else
{
var currentDate = new Date();

//Check whether new date is greater than current date.
if( newDate.getTime() < currentDate.getTime() )
return false;
else
return true;
}
}





9) Number/Numeric Validation :



function isValidNumber(strInput)
{
var validChars = "0123456789.";
var isNumber=true;
var char;

for (i = 0; i < strInput.length && isNumber == true; i++)
{
char = strInput.charAt(i);
if (validChars.indexOf(char) == -1)
isNumber = false;
}

return isNumber;
}




Following code checks whether there are any number in a given string :


var regExp = /[0-9]+/g
var strNumber = new String("93932")

if(regExp.test(strNumber))
{
//There are numbers in strNumber.
}
else
{
//There are no numbers in strNumber.
}





10) String Validation :



function isValidString(strInput)
{
strInput = strInput.replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');

if(strInput == '')
return false;
else
return true;
}





11) Cancel an event :



function onClick()
{
window.event.returnValue = false;
return false;
}





12) Do postback or call server side function :


HTML code :


<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClientClick="onUpdateClick();">



JavaScript code :


function onUpdateClick()
{
var evenArgs = "Server Call";
__doPostBack('<%= btnUpdate.ClientID %>',evenArgs);
}



CSharp (C#) code :


protected void Page_Load(object sender, EventArgs e)
{
string controlName = Request.Params.Get("__EVENTTARGET");
if (!string.IsNullOrEmpty(controlName))
{
if (controlName.Contains("btnUpdate"))
update();
}
}


void updateIssue()
{
string eventArgument = Request.Params.Get("__EVENTARGUMENT");
//do other operations
}





13) Get html element's top/left position :



function getPosition(elementID)
{
var obj = document.getElementById(elementID);
var top = obj.offsetTop;
var left = obj.offsetLeft;

while(obj.offsetParent != null)
{
obj = obj.offsetParent;
top += obj.offsetTop;
left += obj.offsetLeft;
}

alert("Top : " + top + " Left : " + left);
}





14) Types of dialog boxes in JavaScript :


alert


alert("Alert dialog box");



confirm


var response = confirm("Do you want to continue?");
if (response)
{
//true if OK is pressed
}
else
{
//false if Cancel is pressed
}



prompt


var response = prompt('Enter your name : ', 'Avi');
if (response) //Equivalent to --- if( (response != null) && (response != '') )
{
alert("You entered : " + response);
}
else
{
alert("You pressed Cancel or no value was entered.");
}


Reference :
Three Types of Dialog Boxes in JavaScript

No comments:

Google