PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore 560 100 WEB PROGRAMMING Solution Set II Section A 1. This function evaluates a string as javascript statement or expression and either executes it or returns the resulting value. A simple example assigns 25 to a variable. a=eval( 20+1+4 ); 2. The math object allows to perform mathematical tasks. Math.abs() - smath.abs(x) returns the absolute (positive) value of x: Math.ceil(x) - returns the value of x rounded up to its nearest integer: Math.floor() - Math.floor(x) returns the value of x rounded down to its nearest integer: 3. The toexponential() Method - toexponential() returns a string, with a number rounded and written using exponential notation. Ex: var x = 9.656; x.toexponential(2); // returns 9.66e+0 x.toexponential(4); // returns 9.6560e+0 The tofixed() Method - tofixed() returns a string, with the number written with a specified number of decimals: Ex : var x = 9.656; x.tofixed(0); // returns 10 x.tofixed(2); // returns 9.66 The tostring() Method - tostring() returns a number as a string. All number methods can be used on any type of numbers (literals, variables, or expressions): Ex: var x = 123; x.tostring(); // returns 123 from variable x 4. JavaScript can be implemented using JavaScript statements that are placed within the<script>... HTML tags in a web page. <script...> JavaScript code Attributes in script tag Type Src Language 5. The difference between span and div is that a span element is in-line and usually used for a small chunk of HTML inside a line (such as inside a paragraph) whereas a div (division) element is block-line (which is basically equivalent to having a line-break before and after it) and used to group larger chunks of code. Section B 1. There are 4 ways to include javascript code in html. They are: Script in <head>... section. Scripts can be executed when they called, or when an event is triggered, are placed in functions. Ex: <html><head><script...> function message()
alert( this is alert box ); <input type= button value= click here onclick= message() /> Script in... section. <script type= text/javascript > document.write( this is javascript ); Script in... and <head>... sections. We can place an unlimited number of scripts in the document, both in head and body section. Ex: <html><head><script...> function message() alert( this is alert box ); document.write( this is javascript ); <input type= button value= click here onclick= message() /> Script in an external file and then include in <head>... section. We can keep javascript scripts in separate files and use the SRC attribute of the SCRIPT tag to include the javascript program in an HTML file. The src attribute can be used as <script type= text/javascript src= javascript.js > EX: <html><head> <script type= text/javascript src= javascript.js > <input type= button value= click here onclick= message() /> " javascript.js function message() alert( this is alert box ); 2. There are 4 ways to create an instance of Date object. Var newdate= new Date(); This creaes a new instance of the object that contains the current date and time at the command was executed. Var somedate = new Date(milliseconds) milliseconds When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the gettime() method. For example, passing the argument
5000 creates a date that represents five seconds past midnight on 1/1/70. new Date(datestring) - datestring When one string argument is passed, it is a string representation of a date. Ex: var date= new Date( Tue Feb 26 12:29:22 EST 2002 ) new Date(year,month,date[,hour,minute,second,millisecond ]) Date Methods Date() - Returns today's date and time getdate() - Returns the day of the month for the specified date according to local time. getday() - Returns the day of the week for the specified date according to local time. getfullyear() - Returns the year of the specified date according to local time. gethours() - Returns the hour in the specified date according to local time. getmilliseconds() - Returns the milliseconds in the specified date according to local time. getminutes() - Returns the minutes in the specified date according to local time. getmonth() - Returns the month in the specified date according to local time. getseconds() - Returns the seconds in the specified date according to local time. gettime() - Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. 3. onclick Event Type This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type. <html> <head> <!-- function sayhello() alert("hello World") //--> <p>click the following button and see result</p> <form> <input type="button" onclick="sayhello()" value="say Hello" /> </form> </html> onsubmit Event type onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data. <head> <!-- function validation() all validation goes here... return either true or false //-->
<form method="post" onsubmit="return validate()">... <input type="submit" value="submit" /> </form> 4. There are 3 JavaScript methods that can be used to convert variables to numbers: The Number() method The parseint() method The parsefloat() method These methods are not number methods, but global JavaScript methods Global Methods JavaScript global methods can be used on all JavaScript data types. The Number() Method Number() can be used to convert JavaScript variables to numbers: x = true; Number(x); // returns 1 x = false; Number(x); // returns 0 x = "10" Number(x); // returns 10 x = "10 20" Number(x); // returns NaN The parseint() Method parseint() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned: parseint("10"); // returns 10 parseint("10.33"); // returns 10 parseint("10 20 30"); // returns 10 parseint("10 years"); // returns 10 parseint("years 10"); // returns NaN The parsefloat() Method parsefloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned: parsefloat("10"); // returns 10 parsefloat("10.33"); // returns 10.33 parsefloat("10 20 30"); // returns 10 parsefloat("10 years"); // returns 10 parsefloat("years 10"); // returns NaN 5. Forms and arrays are defined in DOM 0. DOM 0 uses the forms and elements array of the Document object which is referenced by the document property of the window object. document.forms[number].elements[number] The next approach of DOM addressing is to use element names. Var doc = document.firstform.elementname We can get the value of any element by using: var_name = document.firstform.elementname.value ex: firstname=document.form1.name.value; in the output the variable firstname is assigned with a value. document.form1.name.value document is the root element that represents the html document.
form1 is the name of the form. name is the attribute name of the input text. value is the property, that returns the value of the input text. Section C 1. A function is a group of reusable code which can be called anywhere in your program. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. Syntax function functionname(parameter-list) statements Calling a Function function sayhello() document.write ("Hello there!"); <p>click the following button to call the function</p> <form> <input type="button" onclick="sayhello()" value="say Hello"> </form> In the example above, the function sayhello() is defined in head section and this function is called from body section of program. When the button is clicked, the function is called andthe statements inside the function are executed. The output after the button clicked is "Hello there!" 2. <html> <head> <script type = "text/javascript"> var num = window.prompt("enter the number:",""); var n = parseint(num); result = sumofnaturalno(n); window.alert("the sum of " + n + " "+ "natural number is" +" = " + result); function sumofnaturalno(n) var i; var sum = 0; for(i = 1;i <= n; i++) sum = sum + i; return (sum); function getconfirm()
var retval = confirm("do you want to continue?"); if( retval == true ) document.write ("User wants to continue!"); return true; else document.write ("User does not want to continue!"); return false; <p>click the following button to see the result: </p> <form> <input type="button" value="click Me" onclick="getconfirm();" /> </form> </html> 3. String object methods with examples. CharAt() - Returns the character at the specified index. CharCodeAt() - Returns a number indicating the Unicode value of the character at the given index. Concat() - Combines the text of two strings and returns a new string. IndexOf() - Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. LastIndexOf() - Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. Slice() - Extracts a section of a string and returns a new string. split() - Splits a String object into an array of strings by separating the string into substrings. Substr() - Returns the characters in a string beginning at the specified location through the specified number of characters.substring() - Returns the characters in a string between two indexes into the string. tolowercase() - Returns the calling string value converted to lower case. touppercase() - Returns the calling string value converted to uppercase. <html> <head> <title>javascript String constructor Method</title> var str = new String( "This is string" ); document.write("<br /> str.length is:" + str.length); document.write("<br />str.charat(9) is:" + str.charat(9)); document.write("<br />str.charcodeat(1) is:" + str.charcodeat(1)); var str2 = new String( "2nd string concatenated with 1st string " ); var str3 = str.concat( str2 ); document.write(" <br />Concatenated String :" + str3); var index = str2.indexof( "string" ); document.write("<br />indexof found String :" + index ); var index = str2.lastindexof( "string" );
document.write("<br />lastindexof found String :" + index ); var sliced = str.slice(3,-2); document.write("<br />"+ sliced); var splitted = str2.split("t", 4); document.write( "<br />" + splitted ); document.write("<br />(1,2): " + str.substr(1,2)); document.write("<br />(0,10): " + str.substring(0, 10)); document.write("<br />" +str.touppercase( )); document.write("<br />" +str.tolowercase( )); </html> 4. Document: Each HTML document loaded nto browser window becomes a Document object. They have the properties like cookies, documentmode, domain, lastmodified, readystae, title, URL. Location: Location object contains info about the current URL. Accessed through the window.location property. They have the properties like host, hostname, href, port, protocol, pathname and search. History: Contains the URLs visited by the user. Window.history property Screen: Contains information about the visitors screen. The properties of screen are height, width, colordepth, availwidth and availheight. Navigator: Contains information about the browser. The properties of navigation object are appcodename, appname, appversion, cookieenabled, platform. Frames: An array of references to the frames of the document. Image : document.images[].property. Link: document.links[].property.