Sie sind auf Seite 1von 13

Javascript

JavaScript code must be placed between <script> and </script> tags.

Where To Place JavaScript :You can place in <body> or the <head> sections in HTML page or also
placed in external files with .js extension

To use an external script <script src="myScript.js"></script>

Note: <script type="text/javascript"> The type attribute is not required. as JavaScript is the default
scripting language in HTML.

Dom Hierarchy

Comments: Single line comments start with //.

Multi-line comments start with /* and end with */.


JavaScript Output :

 Writing into an alert box, using window.alert().


 Writing into the HTML output(page) using document.write().
 Writing into an HTML element, using innerHTML.
 Writing into the browser console, using console.log().

The innerHTML property defines the HTML content

Note: Javascript is case senstive

Variable: To store value.


variable declartion : var var_name=value; var foo = 'hello world';

Arrays: Used to store multiple values in a single variable (Multiple values of the same type (such as
strings,Int).Index start with 0

Note: In JavaScript Arrays are special kinds of objects. So you can have different types of values or diff
objects or functions in an Array.

var myArray = [ 'hello', 'world' ];


var a = new array() // Creates an empty array
var b = new array(8) // Creates an array with 8 element
var c = [1, 2, "turtle", "number", true]; // Creates an array with a bunch of random values
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Javascript Array Properties and Functions

Size of an array: length var myArray = [ 'hello', 'world' ];


console.log(myArray.length); // logs 2

Methods:

1. join(): It joins all elements into a string.


2. sort(): It sorts elements of an array.
3. reverse(): It reverses the order of elements in array.
4. push(): It adds the element to an array (at the end).
5. unshift(): It adds the new element to the array (at the beginning).
6. pop(): It removes the last element from the array.
7. shift(): It removes the first element from the array.
8. Splice(index,how many elements): Remove elements specified index
9. Spilt(): split a string into an array of substrings

Push : var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.push("Lemon"); // adds a new element (Lemon) to fruits

Unshift: var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.unshift("Lemon","Pineapple"); //output: Lemon,Pineapple,Banana,Orange,Apple,Mango

Changing the value of an array item: var myArray = [ 'hello', 'world' ]; myArray[1] = 'changed';

Pop : var myArray = ["7-up", "Sprite", "Ginger Ale", "Lemonade"];

myArray.pop(); console.log(myArray); // ["7-up", "Sprite", "Ginger Ale"]


Shift: var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // output: Orange,Apple,Mango

Splice(): var myArray = ["cassava", "nutmeg", "lupin", "rhubarb"];

myArray.splice(2, 1); // removes 1 element from index 2


console.log(myArray); // ["cassava", "nutmeg", "rhubarb"]

Join: var fruits = ["Lemon","Apple","Orange","Peach"];

var str = fruits.join(': ');alert(str); // Lemon: Apple: Orange: Peach

Spilt: var str = "How are you doing today?";


var res = str.split(" "); // How,are,you,doing,today?

Javascript Date Functions

 a = new Date(); // Creates a new date object and assigns the current time to it
 document.write(a.getTime()); : Returns a millisecond representation of a date. ex.
1270487133410
 document.write(a.getDay()); : Returns the day of the week
 document.write(a.getFullYear()); : Returns the year of the date
 document.write(a.getHours()); : Returns the hours of the set date
 document.write(a.getMinutes()); : Returns the minutes of the set date

 a.setTime(); : Creates a millisecond representation of a date. ex. 1270487133410


 a.setDay(); : Sets the day of the week
 a.setFullYear(); : Sets the year of the date
 a.setHours(); : Sets the hours of the set date
 a.setMinutes(); : Sets the minutes of the set date

Javascript String Functions

Here are a few of the most used string functions.

 stringVariable.length : Returns the number of characters in a string


 stringVariable.charAt(x) : Returns the character at the position sent to this function
 stringVariable.concat(x1, x2) : Adds one or more values to the end of the string
 stringVariable.indexOf(wordYourLookingFor, whereToStartSearch) : Searches the string for a
chosen word or character
 stringVariable.match(regexp) : Look for a specific regular expression in a string. See my
Javascript Regular Expression tutorial if you don’t know what they are.
 stringVariable.replace(regexp, replacementText) : Search for a regular expression match and
then replace the match with the replacement text given
 stringVariable.slice(startPoint, endPoint) : Extracts a string from the beginning point to the
ending point given
 stringVariable.split(delimiter, maxLength) : Breaks a string into a series of cells, by separating
the words by the chosen delimiter. ex. “1,2,3,4″.split(“,”) would return ["1","2","3","4"]. You
have the option of defining a maximum number of elements in the array that is created.

Javascript Document Functions

 document.getElementsByName(idName) : To access an element with id


document.write() : Appends text or variable values to the web page
 document.writeln() : Appends text or variable values to the web page, followed by a
newline

Functions: Unit or block of executable code. Gets execute when called.

Can have parameters. May or may not return values back

Ex: function getsum(a,b) { return a +b;}

Function expression :

JavaScript functions : arguments object

 Along with parameters , arguments object also get passed to a JavaScript function.
 what parameters, how many parameters passed can be find using arguments.
 Value of parameters can be read using the argument indexes.
function ShowTotal() { var s = 0;
for (var i = 0; i < arguments.length;i++){ s+=arguments[i];}
return s;
} document.write(ShowTotal(10,20,30)); </script>

Anonymous functions: Can invoke itself or Self executing functions

(function() { //stmts })();

Example:1. ( function() { alert("This is message"); } )();

2. ( function(a,b) { alert("sum =" + (a +b).toString()); }

) (10,20);

3. var r= (function(a,b)

{ var c=0; c=a-b; return c; })

(20,5);

alert(r.toString());

JavaScript functions : scopes

 A variable which is not defined inside any function is in global scope.


 Variable in the global scope can be used anywhere in the program
 Variable inside a function works in local scope.
 Variable in the local scope are accessible only inside the function
 Scopes
 global
 Functional/local
 lexical

JavaScript functions : this keyword : “this” represents the calling context

In the global scope “this” represents either a document or window object.


JavaScript Objects In JavaScript everything is an object. JavaScript doesn't have classes,we can
create an object from an object.Every object contains a second object called a prototype object.

 Objects can be created in 3 ways.


 Object as literal
 Using the new operator and constructors
 Using the Object.create() static method

Object as literal: Name-value pairs(separated with :) and list with comma-separated ecclosed in curly
braces

var myObject = {
sProp: 'some string value',
numProp: 2,
bProp: false
};
Note:Object literal property values can be of any data type, including arrays, functions, and nested
object
var Swapper = {
// an array literal
images: ["smile.gif", "grim.gif", "frown.gif", "bomb.gif"],
pos: { // nested object literal
x: 40,
y: 300
},
onSwap: function() { // function
// code here
}
};

var foo = {};


foo.prop = "noo";
console.log(foo.prop);
var rectangle = { height: 20, width: 30 };
console.log(rectangle.height);
rectangle.height = 30;
console.log(rectangle.height);

In the above listing, we have created two objects:


1. Object foo does not contain any properties
2. Properties can be added to an object after creation too. In the above listing, when object foo was
created it did not have any properties, so we added a property named “prop” in the foo object.
3. Object rectangle contains two properties: height and width.
4. The value of the properties can be modified after the object creation. In the above listing we modified
the height property.
Complex Object Literal: Create a student object with following properties:
1. Name 2. Age 3. Subject
4. Parents – another object literal with its own properties like name and age.
var student = {
name: "David",
age: 20,
parents: {
name: 'Mark',
age: 58
}
};

var studentparentage = student.parents.age;


console.log(studentparentage);
A single object literal creates as many new object
var fooarr = [];
for (i = 0; i < 10; i++) {

var foo = { val: i };


fooarr.push(foo);
console.log(fooarr[i].val);

}
console.log(fooarr[3].val);

Creating An object using new operator or constructor pattern

function Rectangle(height, width) {


this.height = height;
this.width = width;

this.area = function () {
return this.height * this.width;
};
};

var rec1 = new Rectangle(45, 6);


var rec2 = new Rectangle(8, 7);
var rec1area = rec1.area();
console.log(rec1area);
var rec2area = rec2.area();
console.log(rec2area);

Object Prototypes
All the objects such as functions in JavaScript contain a prototype object. When we use function as
constructor to create object, properties of prototype object get available to the newly created objects.
We can solve the above problem of area function getting redefined using the prototype object of the
constructor.
function Rectangle(height, width) {

this.height = height;

this.width = width; }

Rectangle.prototype.area = function () {
return this.height * this.width; };

var rec1 = new Rectangle(45, 6); var rec2 = new Rectangle(8, 7);

var rec1area = rec1.area(); console.log(rec1area);

var rec2area = rec2.area(); console.log(rec2area);

In above listing we are creating the area function as the property of the Rectangle prototype. Hence it
will be available to all new objects without getting redefined.
Keep in mind that every JavaScript object has a second object associated with it called prototype object.
Always the first objects inherits the properties of the prototype object.
function emp(name){ this.Name=name;
this.getName=function(){
return this.name; } }
var e1=new emp('Mark');
var e2=new emp('shaik');
Problem:if you create 100 emp objects there will be 100 copies of getName() function.
Instead we want all the objects share same function code.
function emp(name){ this.Name=name; }
emp.getName=function(){
return this.name; }}
Advantages:1.No matter how many objects you create,functions are loaded only once into memory.
function emp(name){}
emp.prototype.getname=function(){ return this.name; }
var e1=new emp('Mark');
Object.create()
The Object.create() static method was introduced in ECMA Script 5.0. It is used to construct new object.,
var foo = Object.create(Object.prototype,

{ name: { value: 'koo' } });

console.log(foo.name);

Some important points about Object.create() to remember:


1. This method takes two arguments:
a. The first argument is the prototype of the object to be created, and is the required argument
2. The second arguments is the optional argument, and describes new properties of the newly
created object
3. The first argument can be null, but in that case the new object will not inherit any properties
4. To create an empty object, you must pass the Object. Prototype as the first argument
Let’s say you have an existing object called foo and you want to use foo as a prototype for a new object
called koo with the added property of “food”. You can do so by doing this:
var foo = { name: 'steve', age: 30};

var koo = Object.create(foo,{ subject: { value: 'koo' } });

console.log(koo.name);

console.log(koo.subject);

In the above listing, we have an object named foo, and we’re using foo as the prototype of the object
named koo. Koo will inherit the properties of foo and it will have its own additional properties also.
Accessing Object Properties;

objectName.propertyName or objectName["propertyName"]

JavaScript String Methods:

indexOf() method returns the index of first occurrence of a specified text in a string:

Ex: var str = "Please locate where 'locate' occurs!";


var pos = str.indexOf("locate");

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

Ex: var str = "Please locate where 'locate' occurs!";


var pos = str.lastIndexOf("locate");

Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.

Extracting String Parts:

 slice(start, end)
 substring(start, end)
 substr(start, length)

Slice: 1.var str = "Apple, Banana, Kiwi";


var res = str.slice(7,13); //Banana

2.var str = "Apple, Banana, Kiwi";


var res = str.slice(-12,-6); //Banana

3.var res = str.slice(7);

substring() is similar to slice().The difference is that substring() cannot accept negative indexes.
Example
var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13); //Banana

Note:If you know the indices, use slice(); if you know the length, use substr().

Substr() Method:substr() is similar to slice().The difference is that the second parameter specifies the
length of the extracted part.

var str = "Apple, Banana, Kiwi";


var res = str.substr(7,6); //Banana

Converting a string to an Array: split() method:

var txt = "a,b,c,d,e"; // String


txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe

Note: When you place runat="server" in an standard HTML tag,to get the html element in javascript use

<input type="hidden" id="hdn" value="Some Hidden Value" runat="server" />


<input type="text" id="txtbox" value="" />
<input type="button" id="btn1" value="Click Me" onclick="GetHiddenvalue()" />

function GetHiddenvalue() {

var hdnvalue = document.getElementById("<%=hdn.ClientID%>").value;


document.getElementById('txtbox').innerText = hdnvalue;
}
How to get value of textbox in javascript

var txt_value=document.getElementByid('<%=textbox1.ClientID%>').value;

Diff between Settimeout and setinteval

setTimeout:Execute function after defined time in milliseconds,its execute only once


setInterval: Eecute function in each interval

Q:NaN:Returns true if the arguement is not a number

Q:Call javascript from code behind

scriptmanager.registerstartupscript(page,typeof(page),"message","javascript:alert-msg(function
name);",true);

Q:Pass textbox value from code behind to JavaScript function


function getvalue(id){
var value=getElementByid('id').value;
alert(value);
}

//code behind

scriptmanager.registerstartupscript(page,typeof(page),"message","javascript:getvalue('"
+txt_name.ClientID +"') ",true);

Q:Access session value in javascript

protected void page_load(){ session["Name"]="Vishal";}

function Access_Session_value(){ var name="<%=session["Name"]%>"}

Get Current URL: location.href


Port no:location.port

Stop Timer in javascript:


clearInterval is a static method of windows used to stop

var str=setInterval(function(){start_timer()},3000);

function start_timer(){ alert('hello');}


function stop_timer(){ window.clearInterval(str); }

q:dropdown list select text using javascript

var str=document.getElementByid('<%=ddldropdownlist1.ClientID%>')
var text=str.options[str.selectedindex].text

Sample validation using javascript:

<script type="text/javascript">

function validate() {

var summary = '';


summary += isvalidusername();
summary += isvalidFirstname();
summary += isvalidlocationname();
if (summary != '') { alert(summary); return false; }
else {return true};
}

function isvalidusername() {

var uid;
var temp = document.getElementById('<%=txtfname.ClientID%>');
uid = temp.value;
if (uid == '') { return ("please enter firstname" + "\n"); }
else { return '';}

}
function isvalidFirstname() {

var firstname;
var temp = document.getElementById('<%=txtuser.ClientID%>');
firstname = temp.value;
if (firstname == '') { return ("please enter username" + "\n"); }
else { return ''; }

}
function isvalidlocationname() {

var locname;
var temp = document.getElementById('<%=txtlocation.ClientID%>');
locname = temp.value;
if (locname == '') { return ("please enter location" + "\n"); }
else { return ''; }

}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>UserName</td>
<td><asp:TextBox ID="txtuser" runat="server" /></td>
</tr>
<tr>
<td>First Name</td>
<td><asp:TextBox ID="txtfname" runat="server" /></td>
</tr>
<tr>
<td>Location</td>
<td><asp:TextBox ID="txtlocation" runat="server" /></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnsave" runat="server" Text="Save"
OnClientClick="javascript:validate()" />

</td>
</tr>
</table>
</form>
</body>
</html>

Importantance of returning false


If you do not speficy return false then the message will be displayed to the user that all fields are
required but the form will be post back and it gives you the second page directly. Therefore the return
false statement works similar to the Required Field validator of ASP.Net.

Das könnte Ihnen auch gefallen