Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Validate Textbox Value for Special Character Paste Data

JavaScript Method to Validate '<' and '>' Character on paste data in text box or in Text Area.
Read the Text from clipboard and validate using ValidateText Function.
function OnTextPaste()
{
var data="";
data=window.clipboardData.getData("Text");
if(data)
{
var ret=ValidateText(data);
if(!ret)
alert('Sorry, you can not paste text having <, > in it.');
return ret;
}
else
return false;
}

function ValidateText(str)
{
var ret;
if(str.indexOf('<') != -1)
ret=false;
else if(str.indexOf('>') != -1)
ret=false;
else
ret=true;
return ret;
}

Hide JavaScript Error

This Method is used to Handle JavaScript Error that we don't want to show in case of unavoidable conditions.
Code:
function handleError()
{
return true;
}
window.onerror = handleError;

JavaScript Object Notation (JSON)

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a language independent text format which is fast and easy to understand. JavaScript Object Notation (JSON) is a text format for the serialization of structured data. File extension for json file is *.json

The application/json is media type for JavaScript Object Notation (JSON). JSON can represent four primitive types:
• Strings (double-quoted Unicode with backslash escaping)
• Numbers (integer, real, or floating point)
• Booleans (true and false)
• Null
And two structured types:
• Objects (collection of key:value pairs, comma-separated and enclosed in curly braces)
• Arrays (an ordered sequence of values, comma-separated and enclosed in square brackets)

A JSON text is a serialized object or array.

JSON-text = object / array

These are the six structural characters:

begin-array [ left square bracket

begin-object { left curly bracket

end-array ] right square bracket

end-object } right curly bracket

name-separator : colon

value-separator , comma

The following example shows the JSON representation of an object that describes a person. The object has string fields for first name and last name, contains an object representing the person's address, and contains a list of phone numbers (an array)
.{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
The equivalent for the above in XML:
<Person firstName="John" lastName="Smith">
<Address>
<streetAddress>21 2nd Street</streetAddress>
<city>New York</city>
<state>NY</state>
<postalCode>10021</postalCode>
</Address>
<phoneNumber type="home">
212 555-1234
</phoneNumber>
<phoneNumber type="fax">
646 555-4567
</phoneNumber>
</Person>
JSON is like XML because:
1. They are both 'self-describing' meaning that values are named, and thus 'human readable'
2. Both are hierarchical. (i.e. You can have values within values.)
3. Both can be parsed and used by lots of programming languages
4. Both can be passed around using AJAX (i.e. httpWebRequest)

JSON is Unlike XML because:
1. XML uses angle brackets, with a tag name at the start and end of an element: JSON uses squiggly brackets with the name only at the beginning of the element.
2. JSON is less verbose so it's definitely quicker for humans to write, and probably quicker for us to read.
3. JSON can be parsed trivially using the eval() procedure in JavaScript
4. JSON includes arrays {where each element doesn't have a name of its own}
5. In XML you can use any name you want for an element, in JSON you can't use reserved words from JavaScript

What is good about JSON?
When you're writing Ajax stuff, if you use JSON, then you avoid hand-writing xml. This is quicker.
Again, when you're writing Ajax stuff, which looks easier? The XML approach or the JSON approach:
The XML approach:
1. Bring back an XML document
2. Loop through it, extracting values from it
3. Do something with those values, etc,
The JSON approach:
1. Bring back a JSON string.
2. 'eval' the JSON

TextBox MaxLength Validation and Display Remaining Characters

Text Box OR Text area max length validation and also display the words remaining.
Arguments:
(1) TextBox or Text Area ID
(2) Label ID where we want to show count of remaining character.
(3) Number of Maximum character that are allowed.

Sample Code:
function CountCharactersGeneral(sourceTextBox, displayControl, maxLength)
{
if(sourceTextBox != null && displayControl != null)
{
sourceTextBox = document.getElementById(sourceTextBox);
displayControl = document.getElementById(displayControl);
if(sourceTextBox != null)
{
var len = sourceTextBox.value.length
if (len<=maxLength)
{
displayControl.innerHTML = maxLength -len +" Character(s) remaining.";
}
else
{
sourceTextBox.value = sourceTextBox.value.substring(0, maxLength);
return false;
}
}
}
}

Show Current - Date,Month,Year in JavaScript

This Code will return the Result in numeric form as :
for date 21/8/2009:

objDate.getDate(); will return 21.
objDate.getMonth() + 1 will return 8
objDate.getFullYear() will return 2009

var objDate=new Date();
var today=objDate.getDate();
var month=objDate.getMonth() + 1;
var year=objDate.getFullYear();

Sample Code To Show Today's Detail:
var months = new Array(12);
months[0]="January";
months[1]="February";
months[2]="March";
months[3]="April";
months[4]="May";
months[5]="June";
months[6]="July";
months[7]="August";
months[8]="September";
months[9]="October";
months[10]="November";
months[11]="December";

var days = new Array(7);
days[0]="Sunday";
days[1]="Monday";
days[2]="Tuesday";
days[3]="Wednesday";
days[4]="Thursday";
days[5]="Friday";
days[6]="Saturday";
var objDate=new Date();
var today=objDate.getDay();
var date=objDate.getDate();
var month=objDate.getMonth();
var year=objDate.getFullYear();
document.write("Today is : " + days[today] + ", " + months[month] + " " + date+ ", " + year);
document.write("Current date is : " + today + " / " + month + " / " + year);

Display Random Message on Page Refresh

Show Rendom Message On Page refresh.
Place all the Messages in an Array
Math.floor(Math.random() * 8) function will pick the random record from array.

Sample Code:

<script language="JavaScript" type="text/javascript">
var arMessage = new Array(
'She is a complete waste of space',
'I did not recognize you with your clothes on ',
'If I never see you again, it will be too soon ',
'He is so full of shit, even his eyes are brown',
'You are so far up our managers ass, I can almost see your legs',
'She is as welcome as a turd in a swimmingpool',
'My boss is an accident waiting for a place to happen',
'I would not piss on you, even when you were on fire');
var ind = Math.floor(Math.random() * 8);
document.write('<b class="r">'+arMessage[ind]+'</b>');
</script>

Scaling height width of the object.

In This Sample you need maximum width of the object 1024 and maximum height 750; You need to pass the width and height of object (dblWidth AND dblHeight) and you will get the scaled height and width of the object.

Sample Code:
Double dblWRatio =0

//Actual Width of the Object
Double dblWidth =1280;
//Actual Height of the Object
Double dblHeight =960

//Maximum width of the Object
Double PalyerWidth =1024;
//Maximum height of the Object
Double PlayerHeight =750;

dblWRatio = ((PalyerWidth - dblWidth) * 100) / dblWidth;
dblWidth += dblWidth * (dblWRatio / 100);
dblHeight += dblHeight * (dblWRatio / 100);

if (dblHeight > PlayerHeight)
{
dblHRatio = ((PlayerHeight - dblHeight) * 100) / dblHeight;
dblWidth += dblWidth * (dblHRatio / 100);
dblHeight += dblHeight * (dblHRatio / 100);
}

Javascript- Pop Up window Using the window.open method

The syntax of the window.open method is given below:

window.open (URL, windowName, Features)

URL:
The URL of the page to open in the new window. This argument could be blank.

Window Name:
A name to be given to the new window. The name can be used to
refer this window again.

Features:
A string that determines the various window features to be included
in the pop up window (like status bar, address bar etc)

Code to opens a new browser window with standard features.
window.open ("http://www.google.com","mywindow");

Following are the features of window.open method:
status: status bar at the bottom of the window.(e.g: status=1 or 0)
toolbar: The standard browser toolbar, with buttons such as
Back and Forward. (e.g: toolbar=1 or 0)
location: The Location entry field where you enter the URL.(e.g: location=1 or 0)
menubar: The menu bar of the window (e.g: menubar=1 or 0)
resizable: Allow/Disallow the user to resize the window.(e.g: resizable=1 or 0)
scrollbars: Enable the scrollbars if the document is bigger than the
window(e.g: scrollbars=1 or 0)
height: Specifies the height of the window in pixels. (e.g: height='200')
width: Specifies the width of the window in pixels. (e.g: width='200')

Example:
The following code opens a window with menu bar and toolbar.
The window is resizable and is having 350 pixels width and 250 pixels height.
window.open ("http://www.google.com ",
"mywindow","menubar=1,resizable=1,toolbar=1,
width=350,height=250");

Javascript - Event Handling

This code will help us to write any code before and after any event. BeforeAjaxRequest method will be executed before any event and pageLoadedHandler method will be executed at the end of any event.

Sample Syntax:
var pageMgr = Sys.WebForms.PageRequestManager.getInstance();
pageMgr.add_beginRequest(BeforeAjaxRequest);
pageMgr.add_pageLoaded(pageLoadedHandler);
var postbackElement;

function BeforeAjaxRequest(sender, args)
{
postbackElement=args.get_postBackElement();
if (postbackElement.id.indexOf("{ID of the Control}") != "-1")
{
/* Write your Code Here */}
}

function pageLoadedHandler(sender, args)
{
if (typeof(postbackElement) == "undefined") { return;}
else if (postbackElement.id.indexOf("
{ID of the Control}") != "-1")
{
/* Write your Code Here */}
}


For Example: You are having a asp link button with id lnkTest now according to this your above code should be:
function BeforeAjaxRequest(sender, args)
{
postbackElement=args.get_postBackElement();
if (postbackElement.id.indexOf("
lnkTest") != "-1")
{
alert("Before Ajax Request");}
}

function pageLoadedHandler(sender, args)
{
if (typeof(postbackElement) == "undefined") { return;}
else if (postbackElement.id.indexOf("
lnkTest") != "-1")
{
alert("After Ajax the Request");}
}

Clock in Javascript

To Show Clock in Javascript (Time Format: SAT 4-25-2009 2:43:22 PM)

Function to create a array of given length
function MakeArray(size)
{
this.length = size;
for(var i = 1; i <= size; i++)
{
this[i] = "";
}
return this;
}


Function to display time. in this at the end we write setTimeout("showtime()",1000)
.
this code will call the showtime function after every second.
function showtime ()
{
var now = new Date();
var year = now.getYear();
var month = now.getMonth() + 1;
var date = now.getDate();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var day = now.getDay();
Day = new MakeArray(7);
Day[0]="SUN";
Day[1]="MON";
Day[2]="TUE";
Day[3]="WED";
Day[4]="THU";
Day[5]="FRI";
Day[6]="SAT";
var timeValue = "";
timeValue += (Day[day]) + " ";
timeValue += ((month > 10) ? " 0" : " ") + month + "-";
timeValue += date + "-" + year + " ";
timeValue += ((hours <= 12) ? hours : hours - 12);
timeValue += ((minutes <>
timeValue += ((seconds <>
timeValue += (hours <>
document.getElementById('lblClock').innerHTML = timeValue;
setTimeout("showtime()",1000);
}


Paste the above code in the script tag in Head section and add the following line after the closing of HTML tag:
showtime();

Use a span to show the clock - id of span used in this code is lblClock