Syntax:: Javascript Code
Syntax:: Javascript Code
Syntax:: Javascript Code
</script>
Operators:
<script type="text/javascript">
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
document.write("a / b = ");
document.write("a % b = ");
document.write("a + b + c = ");
Conditional Statements-
i) if
ii) else
iii) else if
iv) switch
Loop-
i) for
ii) while
iii) do-while
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5) {
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body> </html>
Functions in JavaScript-
function functionname (parameter1, para2…..)
{
// function body
}
Ex:
function showMessage ()
{
alert(‘hello everyone!’)
}
Local variables: A variable declared inside a function is only visible
inside that function.
<script>
function showMessage()
{
message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error! The variable is local to the function
</script>
Global variables: Variables declared outside of any function ,such as the
outer, username in the code above are called global.
<script>
userName = 'John';
function showMessage()
{
message = 'Hello, ' + userName;
alert(message);
}
showMessage(); // Hello, John
</script>
The return Statement
If you want to return a value from a function.
return value;
For example, the following line causes a runtime error because here
the syntax is correct, but at runtime, it is trying to call a method that
does not exist.
3) Logical Errors -try...catch...finally
<script type = "text/javascript">
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
</script>
<html> <head><script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );}
catch ( e ) {
alert("Error: " + e.description ); }}
</script></head> <body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
<html><head> <script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a ); }
catch ( e ) {
alert("Error: " + e.description ); }
finally {
alert("Finally block will always execute!"}}
</script> </head><body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form></body></html>
Array
Declaration of an Array-basically two ways to declare an array.
1] var house = [ ];
2] var house = new Array( );
Initialization of an Array-
1] var house = [‘1BHK’, ‘2BHK’, ‘3BHK’ ];
house[0] = 1BHK;
house[1] = 2BHK;
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
} </script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
document.getElementsByTagName() method
• The document.getElementsByTagName() method returns all the element of
specified tag name.
document.getElementsByTagName("name")
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length); }
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by
getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Javascript - innerHTML
The innerHTML property can be used to write the dynamic html on the html
document.
<html><body>
<script type="text/javascript" >
function showcommentform() {
var data="Name:<br><input type='text' name='name'><br>Comment:<br><textarea
rows='5' cols='50'></textarea><br><input type='submit' value='comment'>";
document.getElementById('mylocation').innerHTML=data; } </script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
</body></html>
Show/Hide Comment Form Example using innerHTML
<script>
var flag=true;
function commentform(){
var cform="<form action='Comment'>Enter Name:<br><input type='text' name='name'/><br/>
Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<br/>
<textarea rows='5' cols='70'></textarea><br><input type='submit' value='Post Comment'/></form>";
if(flag){
document.getElementById("mylocation").innerHTML=cform;
flag=false;
}else{
document.getElementById("mylocation").innerHTML="";
flag=true; } }
</script> </head> <body>
<button onclick="commentform()">Comment</button>
<div id="mylocation"></div> </body> </html>
innerText
• The innerText property can be used to write the dynamic text on the
html document. Here, text will not be interpreted as html text but a
normal text.
• It is used mostly in the web pages to generate the dynamic content
such as writing the validation message, password strength etc.
<html><body><script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor"; }
document.getElementById('mylocation').innerText=msg; }
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form> </body></html>
<html><body><script>-VALIDATION
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
} } </script> <body>
<form name="myform" method="post" action="http://www.google.com/javascriptpages/valid.jsp"
onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register"> </form> </body></html>
Retype Password Validation
<html><head> <script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;}
else{
alert("password must be same!");
return false;}}
</script></head><body>
<form name="f1" action="http://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>
email validation
We can validate the email by the help of JavaScript.
There are many criteria that need to be follow to validate the email id
such as:
• email id must contain the @ and . character
• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).
<script>
function validateemail() {
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
} }
</script>
<body>
<form name="myform" method="post" action="http://www.google.com/javascriptpages/valid.jsp"
onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register"> </form> </body>
JavaScript this keyword
The this keyword is a reference variable that refers to the current object.
<script>
var address=
{
company:"Javascript",
city:"Noida",
state:"UP",
fullAddress:function()
{
return this.company+" "+this.city+" "+this.state;
} };
var fetch=address.fullAddress();
document.writeln(fetch);
</script>
Global Context
In global context, variables are declared outside the function. Here, this
keyword refers to the window object.
<script>
var website=“yahoo";
function web()
{
document.write(this.website);
}
web();
</script>
The call() and apply() method
<script>
var emp_address = {
fullAddress: function() {
return this.company + " " + this.city+" "+this.state;
}
}
var address = {
company:"Javascript",
city:"Noida",
state:"UP", }
document.writeln(emp_address.fullAddress.call(address));
</script>