Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Javascript Myth

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

JavaScript Data Types:

One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language. JavaScript allows you to work with three primitive data types: * Numbers eg. 123, 120.50 etc. * Strings of text e.g. "This text string" etc. * Boolean e.g. true or false. JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will see an object detail in a separate chapter. Note: Java does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floatingpoint format defined by the IEEE 754 standard. JavaScript Variables: Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows: <script type="text/javascript"> var money; var name; </script> You can also declare multiple variables with the same var keyword as follows: <script type="text/javascript"> var money, name; </script> Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or later point in time when you need that variable as follows: For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable you can assign a value the time of initialization as follows: <script type="text/javascript"> var name = "Ali"; var money; money = 2000.50; </script> Note: Use the var keyword only for declaration or initialization once for the life of any variable name in a document. You should not re-declare same variable twice. JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically. To understand variables in better way you can Try it yourself. JavaScript Variable Scope: The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

* Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code. * Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Following example explains it: <script type="text/javascript"> var myVar = "global"; // Declare a global variable function checkscope( ) { var myVar = "local"; // Declare a local variable document.write(myVar); } </script> This produces the following result: local To understand variable scope in better way you can Try it yourself. JavaScript Variable Names: While naming your variables in JavaScript keep following rules in mind. * You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid. * JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but _123test is a valid one. * JavaScript variable names are case sensitive. For example, Name and name are two different variables.

JavaScript Myth
Common Myths about JavaScript 1. JavaScript == Java UK developer Jeremy Keith devised the best explanation: Java is to JavaScript as ham is to hamster. The names are confusingly similar but Java and JavaScript are not related. There are a number of superficial similarities, but the same can be said for any language adopting a C-like syntax. The language was originally named Mocha, became LiveScript, and finally JavaScript at a time when Java was heralded as the savior to life, the universe and everything. The name reflected Netscapes marketing efforts not any underlying relationship. 2. JavaScript is a toy language The script part of the name gives the impression that JavaScript is some type of cut-down, macrolike or less capable version of Java. Its not. If anything, popular JavaScript features such as closures and lambda functions are now finding their way into other languages (PHP, C# and Java itself). JavaScript is most commonly found as a browser-based interpreted language, but that doesnt mean its any less powerful or competent than an OS-based compiled language. 3. JavaScript is only found in browsers Most people experience JavaScript as an embedded browser language but it (or languages based on the ECMAScript standard) can be found in many other places, e.g. * Mozillas Firefox browser and Thunderbird email client use JavaScript for some application processes * Flash ActionScript is based on JavaScript * PDF files can have JavaScript embedded * Many Microsoft and Apple desktop widgets use JavaScript

* OpenOffice.org provides JavaScript support * webOS, used in Palm mobiles, uses JavaScript for its application framework * JavaScript can be used as an application programming language on the GNOME desktop and as a scripting language in Windows. JavaScript does not have a strong server-side presence but several dozen implementations exist. The day well be able to develop JavaScript on the client and the server cant come soon enough! 4. JavaScript is inconsistent and buggy Those days are long gone. Browser vendors adhere to an agreed standard (ECMAScript) and JavaScript-specific issues are rare. However, browser features are not always consistent: DOM manipulation particularities, event handling idiosyncrasies, and browser quirks all cause development headaches. Thats not a fault with the language itself, but the browser objects you can access with JavaScript. 5. JavaScript is not object-orientated Confusion arises because JavaScript does not provide obvious class-orientated inheritance. The lack of a class keyword causes many developers to assume JavaScript is a functional language. JavaScript offers prototypal inheritance. The real beauty is that you can write functional language code or use classical inheritance patterns with private properties and methods. Furthermore, everything in JavaScript is an object including native types and functions. How many other languages offer constructs such as: var x = new Number(123); var opp = "oops".substr(0,3); var f = function() { return function() { alert("hello!"); }; }; What about passing a function as a parameter (its just another object) var Add = function(a, b) { return a + b; }; function Calculate(func, a, b) { return func(a, b); } var s = Calculate(Add, 1, 2); // s = 3 Or perhaps extending native types // reverse any string String.prototype.Reverse = function() { return this.split("").reverse().join(""); }; var h1 = "Hello!"; var h2 = h1.Reverse(); // !olleH JavaScript can be a little confusing at first but youll miss its elegance and power when you return to other languages.

JavaScript Prototype
First of all we have to realize that a function is not just a function in the traditional sense, it is but at the same time it isnt, its just that the choice of wording is horrible, anything but function would have been better. Anyway, the *function* keyword in JavaScript can basically function as the *class* word in other languages. Lets take a look at a simple example: function Human(name, age){ this.name = name; this.age = age; this.isRetired = function(){ return this.age > 65 ? true : false; } }

Harry = new Human("Harry", 50); document.writeln(Harry.isRetired()); So the function can be instantiated, super weird I know, imagine I had written *class Human* instead or something. Note also the assignment of a function to a member variable in the form of *isRetired*, completely legal, it seems that an unnamed *function()* can be assigned to a variable just like everything else. Thats why we can do the following too: Harry.toStr = function(){ return "Name: " + this.name + ", Age: " + this.age; } document.writeln(Harry.toStr()); Cool, we get his name and age alright. Now try this: Barry = new Harry.constructor("Barry", 70); // Same as new Human("Barry", 70); document.writeln(Barry.toStr()); Oops, *Barry.toStr is not a function*, thats because were really just creating another human, since *toStr* was added to Harry, Barry wont have access to this functionality. To solve this problem the famous *prototype*keyword can be used: Human.prototype.toStr = function(){ return "Name: " + this.name + ", Age: " + this.age; } Barry = new Harry.constructor("Barry", 70); // Same as new Human("Barry", 70); document.writeln(Barry.toStr()); We basically added toStr() to the Human class here, or prototype in this case, that is what that initial Human function is, a prototype, or blueprint if youre an architect. Remember the above way of creating a new Human object with the help of *instance.constructor()*, it will become very important shortly. Keep the above prototype statement and add this below: Harry.toStr = function(){ return "Harry here. Name: " + this.name + ", Age: " + this.age; } document.writeln(Harry.toStr()); So the prototype was locally overridden like we would expect. Lets take a look at how a simple inheritance system based on instances instead of prototyping can be constructed, if you want classical inheritance through prototyping mania, by all means, follow the above link and dig in [image: :)] Object.prototype.extend = function(o) { var obj = new this.constructor(); var me = eval(uneval(this)); for(var key in me) obj[key] = me[key]; for(var key in o) obj[key] = o[key]; obj.parent = o.parent ? o.parent : eval(uneval(this)); return obj; }

JavaScript Date Today (Current)


To warm up our JavaScript Date object skills, let's do something easy. If you do not supply any arguments to the Date constructor (this makes the Date object) then it will create a Date object based on the visitor's internal clock. HTML & JavaScript Code:

<h4>It is now <script type="text/javascript"> var currentTime = new Date() </script> </h4> Display: It is now Nothing shows up! That's because we still don't know the methods of the Date object that let us get the information we need (i.e. Day, Month, Hour, etc). Get the JavaScript Time The Date object has been created, and now we have a variable that holds the current date! To get the information we need to print out, we have to utilize some or all of the following functions: - *getTime()* - Number of milliseconds since 1/1/1970 @ 12:00 AM - *getSeconds()* - Number of seconds (0-59) - *getMinutes()* - Number of minutes (0-59) - *getHours()* - Number of hours (0-23) - *getDay()* - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday - *getDate()* - Day of the month (0-31) - *getMonth()* - Number of month (0-11) - *getFullYear()* - The four digit year (1970-9999) Now we can print out the date information. We will be using the *getDate*, *getMonth*, and *getFullYear* methods in this example. HTML & JavaScript Code: <h4>It is now <script type="text/javascript"> var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() document.write(month + "/" + day + "/" + year) </script> </h4> Display: It is now 9/4/2010 ! Notice that we added 1 to the *month* variable to correct the problem with January being 0 and December being 11. After adding 1, January will be 1, and December will be 12. JavaScript Current Time Clock Now, instead of displaying the date we, will display the format you might see on a typical digital clock -HH:MM AM/PM (H = Hour, M = Minute). HTML & JavaScript Code: <h4>It is now <script type="text/javascript"> var currentTime = new Date() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() if (minutes < 10){ minutes = "0" + minutes } document.write(hours + ":" + minutes + " ") if(hours > 11){ document.write("PM") } else { document.write("AM")

} </script> </h4> Display: It is now 20:34 PM Above, we check to see if either the *hours* or *minutes* variable is less than 10. If it is, then we need to add a zero to the beginning of minutes. This is not necessary, but if it is 1:01 AM, our clock would output "1:1 AM", which doesn't look very nice at all!

HTML Forms
Forms are a vital tool for the webmaster to receive information from the web surfer, such as: their name, email address, credit card, etc. A form will take input from the viewer and depending on your needs; you may store that data into a file, place an order, gather user statistics, register the person to your web forum, or maybe subscribe them to your weekly newsletter. Text Fields Before we teach you how to make a complete form, let's start out with the basics of forms. Input fields are going to be the meat of your form's sandwich. The <input> has a few attributes that you should be aware of. Type:- Determines what kind of input field it will be. Possible choices are text, submit, and password. Name:- Assigns a name to the given field so that you may reference it later. Size:- Sets the horizontal width of the field. The unit of measurement is in blank spaces. Maxlength:- Dictates the maximum number of characters that can be entered. <form method="post" action="mailto:yourem...@email.com"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"> <input type="submit" value="Send"> </form> Radio Buttons Radio buttons are a popular form of interaction. You may have seen them on quizzes, questionnaires, and other web sites that give the user a multiple choice question. Below are a couple attributes you should know that relate to the radio button. Value:- specifies what will be sent if the user chooses this radio button. Only one value will be sent for a given group of radio buttons (see "name" for more information). Name:- Defines which set of radio buttons that it is a part of. Below we have 2 groups: shade and size. <form method="post" action="mailto:yourem...@email.com"> What kind of shirt are you wearing? <br /> Shade: <input type="radio" name="shade" value="dark">Dark <input type="radio" name="shade" value="light">Light <br /> Size: <input type="radio" name="size" value="small">Small <input type="radio" name="size" value="medium">Medium <input type="radio" name="size" value="large">Large <br /> <input type="submit" value="Email Myself"> </form> Check Boxes Check boxes allow for multiple items to be selected for a certain group of choices. The check box's "name" and "value" attributes behave the same as a radio button.

<form method="post" action="mailto:youremail@email.com"> Select your favorite cartoon characters. <input type="checkbox" name="toon" value="Goofy">Goofy <input type="checkbox" name="toon" value="Donald">Donald <input type="checkbox" name="toon" value="Bugs">Bugs Bunny <input type="checkbox" name="toon" value="Scoob">Scooby Doo <input type="submit" value="Email Myself"> </form> Drop Down Lists Drop down menues are created with the <select> and <option> tags. <select> is the list itself and each <option> is an available choice for the user. <form method="post" action="mailto:youremail@email.com"> College Degree? <select name="degree"> <option>Choose One</option> <option>Some High School</option> <option>High School Degree</option> <option>Some College</option> <option>Bachelor's Degree</option> <option>Doctorate</option> <input type="submit" value="Email Yourself"> </select> </form> Selection Forms Yet another type of form, a highlighted selection list. This form will post what the user highlights. Basically just another type of way to get input from the user. The "size" attribute selects how many options will be shown at once before needing to scroll, and the "selected" option tells the browser which choice to select by default. <form method="post" action="mailto:youremail@email.com"> Musical Taste <select multiple name="music" size="4"> <option value="emo" selected>Emo</option> <option value="metal/rock" >Metal/Rock</option> <option value="hiphop" >Hip Hop</option> <option value="ska" >Ska</option> <option value="jazz" >Jazz</option> <option value="country" >Country</option> <option value="classical" >Classical</option> <option value="alternative" >Alternative</option> <option value="oldies" >Oldies</option> <option value="techno" >Techno</option> </select> <input type="submit" value="Email Yourself"> </form> Upload Forms First of all, to actually make the upload form function correctly you must know a scripting language of some sort. PHP and PERL work fine, Javascript is also an option. We have an entire upload example demonstrated here, PHP File Upload <http://www.tizag.com/phpT/fileupload.php>. The HTML code for the upload form does nothing more than create an interface for the user to see and work with. An upload form consists of three basic parts. The first being a hidden field. This hidden field does nothing more than limit the allowed file size of our uploaded file. The second part is the input field itself. In this field, the user has the option to type in the full local URL of the file or he/she may click the *browse* button to thumb

through directory after directory. HTML codes this automatically when we place the type="file"*attribute within the input tag. <input type="hidden" name="MAX_FILE_SIZE" value="100" /> <input name="file" type="file" /> Text Areas Text areas serve as an input field for viewers to place their own comments onto. Forums and the like use text areas to post what you type onto their site using scripts. For this form, the text area is used as a way to write comments to somebody. *Rows* and *columns* need to be specified as attributes to the <textarea> tag. Rows are roughly 12pixels high, the same as in word programs and the value of the columns reflects how many characters wide the text area will be. i.e. The example below shows a text area 5 rows tall and 20 characters wide. Another attribute to be aware of is the *wrap*. Wrap has 3 values. Wrap:- (off/virtual/physical) "Virtual" means that the viewer will see the words wrapping as they type their comments, but when the page is submitted to you, the web host, the document sent will not have wrapping words. *Physical* means that the text will appear both to you, the web host, and the viewer including any page breaks and additional spaces that may be inputed. The words come as they are. *Off* of course, turns off word wrapping within the text area. On ongoing line. <form method="post" action="mailto:youremail@email.com"> <textarea rows="5" cols="20" wrap="physical" name="comments"> Enter Comments Here </textarea><input type="submit" value="Email Yourself"> </form> Also note that any text placed between the opening and closing textarea tags will show up inside the text area when the browser views it.

Form Validation
Lets write following code into the page named "sampleform.html". <html> <head><title>A Simple Form with JavaScript Validation</title> <script type="text/javascript"> function validate_form( ){ valid = true; if ( document.contact_form.contact_name.value == "" ) { alert ( "Please fill in the 'Your Name' box." ); valid = false; } return valid; } </script> </head> <body bgcolor="#FFFFFF"> <form name="contact_form" method="post" onSubmit="return validate_form ( );" action="/cgibin/articles/development/javascript/form-validation-with-javascript/contact_simple.cgi" > <h1>Please Enter Your Name</h1> <p>Your Name: <input type="text" name="contact_name"></p> <p><input type="submit" name="send" value="Send Details"></p> </form>

</body> </html>

E-mail Validation Now, write the following code in your new HTML file: <html> <head><title>A Simple Form with JavaScript Validation</title> <script type="text/javascript"> function validate(form_id,email) { var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var address = document.forms[form_id].elements[email].value; if(reg.test(address) == false) { alert('Invalid Email Address'); return false; } } </script> </head> <body bgcolor="#FFFFFF"> <form id="form_id" method="post" action="action.php" onsubmit="javascript:return validate('form_id','email');"> <input type="text" id="email" name="email" /> <input type="submit" value="Submit" /> </form> </body> </html> Dialog Boxes (i.e. Windows Object) Now, write the following code in your new HTML file: <head> <script type="text/javascript"> function prompter() { var reply = prompt("Hey there, good looking stranger! What's your name?", "") alert ( "Nice to see you around these parts " + reply + "!") confirm ( "Nice to see you around these parts " + reply + "!") } </script> </head> <body> <input type="button" onclick="prompter()" value="Say my name!"> </body>

Calculator Now, write the following code in your new HTML file: <html> <head><title>Calculator</title> <script language="javascript"> var inputstring=" " function updatestring(value){ inputstring += value; document.calculator.input.value=inputstring; } </script> </head> <body background=flow-yellow.jpg> <form name="calculator"> <table border=5 bordercolor=pink bgcolor="#ffffcc"><tr ><td> <input type="text" name="input" maxlength=15 size=27><br /> <input type="button" value=" clear " onclick="input.value=' '; inputstring=' ' "> <input type="button" value=" mod " onclick="updatestring('%')"> <input type="button" value=" * " onclick="updatestring('*')"><br /> <input type="button" value=" 7 " onclick="updatestring('7')"> <input type="button" value=" 8 " onclick="updatestring('8')"> <input type="button" value=" 9 " onclick="updatestring('9')"> <input type="button" value=" / " onclick="updatestring('/')"><br /> <input type="button" value=" 4 " onclick="updatestring('4')"> <input type="button" value=" 5 " onclick="updatestring('5')"> <input type="button" value=" 6 " onclick="updatestring('6')"> <input type="button" value=" - " onclick="updatestring('-')"><br /> <input type="button" value=" 1 " onclick="updatestring('1')"> <input type="button" value=" 2 " onclick="updatestring('2')"> <input type="button" value=" 3 " onclick="updatestring('3')"> <input type="button" value=" + " onclick="updatestring('+')"><br /> <input type="button" value=" 0 " onclick="updatestring('0')"> <input type="button" value=" 00 " onclick="updatestring('00')"> <input type="button" value=" . " onclick="updatestring('.')"> <input type="button" value=" = " onclick="input.value=eval(inputstring);"> </td></tr> </table> </form> </body> </html> JavaScript Notes Image Rollover Now, write the following code in your new HTML file: <html> <head><title>test</title> <script language="JavaScript" type="text/javascript"> if (document.images) { homebuttonup = new Image(); homebuttonup.src = "home1.jpg" ; homebuttondown = new Image() ; homebuttondown.src = "home2.jpg" ; }

function buttondown( buttonname ) { if (document.images) { document[ buttonname ].src = eval( buttonname + "down.src" ); } } function buttonup ( buttonname ) { if (document.images) { document[ buttonname ].src = eval( buttonname + "up.src" ); } } </script> </head> <body> <a href="index.html" onMouseover="buttondown('homebutton')" onnMouseout="buttonup('homebutton')"><img src="home1.jpg" name="homebutton" border="0" /> </a> </body> </html>

You might also like