Web Programming Training By OM SIR Call for free Demo :9320957717/18

JAVASCRIPT COMPLETE TUTORIALS FOR BEGINNERS

(1)Variable example in javascript:
<html>
                <head>
               
                <script> 
                var x = 10;           
                var y = 20; 
                var z=x+y; 
                document.write(z); 
                </script> 
</head>
<body>
</body>
</html>

(2)Global variable example:

<html>
                <head>
                <script> 
                var data=200;//gloabal variable 
                function a(){ 
                document.writeln(data); 
                } 
                function b(){ 
                document.writeln(data); 
                } 
                a();//calling JavaScript function 
                b(); 
                </script>
                </head>
                <body>
                </body>
                </html>

(3)simple array example:

<script>
               
                var emp=["Sonoo","Vimal","Ratan"];

document.write(emp[0]+"<br>");
document.write(emp[1]+"<br>");
document.write(emp[2]);

</script>   
          
(4)New keyword using array example:

<script> 
                var  i; 
                var emp = new Array(); 
                emp[0] = "Arun"; 
                emp[1] = "Varun"; 
                emp[2] = "John"; 
                document.write(emp[0]+"<br>");
                document.write(emp[1]+"<br>");
                document.write(emp[2]+"<br>");
</script> 


(5)array  constructor :

<script> 
                var  emp=new Array("Jai","Vijay","Smith"); 
               
                document.write(emp[0] + "<br>"); 
                document.write(emp[1] + "<br>");
                document.write(emp[2] + "<br>");
                 
                </script> 

(6)function example:

<script> 
                function msg(){ 
                alert("hello! this is message"); 
                } 
                </script> 
                <input type="button" onclick="msg()" value="call function"/>

(7)argument function:

<script> 
                function getcube(number){ 
                alert(number*number*number); 
                } 
                </script> 
                <form> 
                <input type="button" value="click" onclick="getcube(4)"/> 
                </form> 

(8)return  function:

<script> 
                function getInfo(){ 
                return "hello javatpoint! How r u?"; 
                } 
                </script> 
                <script> 
                document.write(getInfo()); 
                </script> 

(9)alert example:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display an alert box:</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>

</body>
</html>

(10)confirm example:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a confirm box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x;
    if (confirm("Press a button!") == true) {
        x = "You pressed OK!";
    } else {
        x = "You pressed Cancel!";
    }
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

(11)Prompt  example:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to demonstrate the prompt box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var person = prompt("Please enter your name", "Harry Potter");
   
    if (person != null) {
        document.getElementById("demo").innerHTML =
        "Hello " + person + "! How are you today?";
    }
}
</script>

</body>
</html>

(12)if example:

<html>
   <body>
     
      <script type="text/javascript">
        
            var age = 20;
        
            if( age > 18 ){
               document.write("<b>Qualifies for driving</b>");
            }
     
      </script>
     
     
   </body>
</html>

(13)if else example:

<html>
   <body>
  
      <script type="text/javascript">
        
            var age = 20;
        
            if( age > 18 ){
               document.write("<b>Qualifies for driving</b>");
            }
           
            else{
               document.write("<b>Does not qualify for driving</b>");
            }
        
      </script>
      </body>
</html>

(14)else if example :

<html>
   <body>
   <script type="text/javascript">
        
            var book ="history";
            if( book == "history" ){
               document.write("<b>History Book</b>");
            }
        
            else if( book == "maths" ){
               document.write("<b>Maths Book</b>");
            }
        
            else if( book == "economics" ){
               document.write("<b>Economics Book</b>");
            }
        
            Else
            {
               document.write("<b>Unknown Book</b>");
            }
        
      </script>
 </body>
<html>



(15)switch  example :

<html>
   <body>
  
      <script type="text/javascript">
        
            var grade='B';
            document.write("Entering switch block<br />");
            switch (grade)
            {
               case 'A': document.write("Good job<br />");
               break;
           
               case 'B': document.write("Pretty good<br />");
               break;
           
               case 'C': document.write("Passed<br />");
               break;
           
               case 'D': document.write("Not so good<br />");
               break;
           
               case 'F': document.write("Failed<br />");
               break;
           
               default:  document.write("Unknown grade<br />");
                                                   break;
            }
                                               
</script>
 </body>
</html>

(16)for loop example:

<html>
   <body>
     
      <script type="text/javascript">
    
            var count;
            document.write("Starting Loop" + "<br />");
        
            for(count = 0; count < 10; count++){
               document.write("Current Count : " + count );
               document.write("<br />");
            }
        
            document.write("Loop stopped!");
   
      </script>
     
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

(17)while loop example:

<html>
  <body>
   <script type="text/javascript">
        
            var count = 0;
            document.write("Starting Loop ");
        
            while (count < 10){
               document.write("Current Count : " + count + "<br />");
               count++;
            }
         document.write("Loop stopped!");
         </script>
      </body>
</html>

(18)do while :

<html>
   <body>
   <script type="text/javascript">
        
            var count = 0;
           
            document.write("Starting Loop" + "<br />");
            do{
               document.write("Current Count : " + count + "<br />");
               count++;
            }
           
            while (count < 5);
            document.write ("Loop stopped!");
        </script>
     </body>
</html>

(19)Simple Object    Example   :

<script> 
                emp={id:102,name:"Shyam Kumar",salary:40000} 
                document.write(emp.id+" "+emp.name+" "+emp.salary); 
                </script> 





 (20)object using new keyword:

<script> 
var emp=new Object(); 
emp.id=101; 
emp.name="Ravi Malik"; 
emp.salary=50000; 
document.write(emp.id+" "+emp.name+" "+emp.salary); 
</script>

(21)Object  Constructor example:
                <script> 
                function emp(id,name,salary){ 
                this.id=id; 
                this.name=name; 
                this.salary=salary; 
                } 
                e=new emp(103,"Vimal Jaiswal",30000); 
                document.write(e.id+" "+e.name+" "+e.salary); 
                </script>


(22)addition of two number using form using JavaScript :

n1<input type = "number" id = "n1" value=15 />
n2<input type = "number" id = "n2" value=20 />

<p>Sum?</p>

<button onclick="sum()">Try it</button>
<p id="demo2">Result?? </p>


<script type="text/javascript">
 function sum()
{
    var fn, ln;
    fn = parseInt(document.getElementById("n1").value);
    ln = parseInt(document.getElementById("n2").value);
    result =  (fn+ln);
    document.getElementById("demo2").innerHTML = result;
}
</script>


Another example for addition  using name  of  field  using  parseInt() function :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script language="Javascript">
function showResult()
{
a = document.Order.Mortgage.value;
b = document.Order.Debt.value;
c = document.Order.Income.value;
d = document.Order.Years.value;
Total = document.Order.Total.value = parseInt(a) + parseInt(b) + parseInt(c)+parseInt(d);
}
</script>
</head>
<body>
<pre>
<form name="Order" action="" method="POST" enctype="text/plain"><br>
<font color=000099 size="4">Mortgage</font>   <input type=text name="Mortgage"   size="20"><br>
<font color=000099 size="4">Debt</font>   <input type=text name="Debt"   size="20"><br>
<font color=000099 size="4">Income</font>     <input type=text name="Income" size="20"><br>
<font color=000099 size="4">Years</font>      <input type=text name="Years"   size="20"><br>
<font color=000099 size="4">Total</font>      <big>$</big><INPUT maxLength="8" size="7" name="Total"><br>
<INPUT name="Submit"  type="button" class="style2" onclick="javascript:showResult();" value="Submit">
</form>
</pre>
</body>
</html>
--------------------------------------------------------------------------------------------------------------------------
Same  example for addition  using name  of  field  using  parseFloat() function :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script language="Javascript">
function showResult()
{
a = document.Order.Mortgage.value;
b = document.Order.Debt.value;
c = document.Order.Income.value;
d = document.Order.Years.value;
Total = document.Order.Total.value = parseFloat(a) + parseFloat(b) + parseFloat(c)+parseFloat(d);
}
</script>
</head>
<body>
<pre>
<form name="Order" action="" method="POST" enctype="text/plain"><br>
<font color=000099 size="4">Mortgage</font> <input type=text name="Mortgage"   size="20"><br>
<font color=000099 size="4">Debt</font><input type=text name="Debt"   size="20"><br>
<font color=000099 size="4">Income</font> <input type=text name="Income" size="20"><br>
<font color=000099 size="4">Years</font><input type=text name="Years"   size="20"><br>
<font color=000099 size="4">Total</font><big>$</big><INPUT maxLength="8" size="7" name="Total"><br>
<INPUT name="Submit"  type="button" class="style2" onclick="javascript:showResult();" value="Submit">
</form>
</pre>
</body>
</html>

--------------------------------------------------------------------------------------------------------------------------
another exmaple for simple calculator using else-if:

<form name=myform>
n1<input type = "number"  name= "n1" value=15 />
n2<input type = "number"  name= "n2" value=20 />

<select  name=cal>
<option value=1>Add</option>
<option value=2>sub</option>
<option value=3>Division</option>
<option value=4>Multiplication</option>
</select>



<button onclick="sum()">Try it</button>
</form>


<script type="text/javascript">

function sum()
{

var  n1=parseInt(document.myform.n1.value);
var  n2=parseInt(document.myform.n2.value);

if(document.myform.cal.value=="1")
{

alert(parseInt(n1+n2));

}


else if(document.myform.cal.value=="2")

{

 alert(parseInt(n1-n2));


}

else if(document.myform.cal.value=="3")

{

 alert(parseInt(n1/n2));

}


else if(document.myform.cal.value=="4")

{

 alert(parseInt(n1*n2));

}

else 

{

alert('no cal');

}

 }


</script>

--------------------------------------------------------------------------------------------------------------------------
another exmaple for simple calculator using switch :
========================================================================
<form name=myform>
n1<input type = "number"  name= "n1" value=15 />
n2<input type = "number"  name= "n2" value=20 />

<select  name=cal>
<option value=1>Add</option>
<option value=2>sub</option>
<option value=3>Division</option>
<option value=4>Multiplication</option>
</select>



<button onclick="sum()">Try it</button>
</form>


<script type="text/javascript">

function sum()
{

var  n1=parseInt(document.myform.n1.value);
var  n2=parseInt(document.myform.n2.value);
   var cal=parseInt(document.myform.cal.value);
   switch(cal)
   {
 
   case  1:

alert(parseInt(n1+n2));
break;
case 2:

alert(parseInt(n1-n2));

break;


case 3:

 alert(parseInt(n1/n2));

break;


case 4:

 alert(parseInt(n1*n2));

break;

default:



alert('no cal');

break;

 }

 }


</script>


========================================================================
-------------------------------------------------------------------------------------------------------------------------
From validation code in javascript :



<html>
<head>
<title>
Simple Client Side Validation
</title>
<script  type="text/javascript">

function  valid()
{

if(myform.name.value=="")
{

alert("enter your name");

return false;

document.myform.name.focus();
}


if(myform.contact.value=="")
{
alert("enter your contact");
return false;
document.myform.contact.focus();
}
if(isNaN(myform.contact.value))
{

alert("enter numeric value in contact");
return false;
document.myform.contact.focus();
}

if(myform.city.value=="")
{

alert("enter your city");

return false;

document.myform.city.focus();

}

if(myform.email.value=="")
{

alert("enter your email");

document.myform.email.focus();

return false;

}



if(myform.address.value=="")
{

alert("enter your address");

document.myform.address.focus();

return false;

}

var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(!myform.email.value.match(mailformat))

{
alert("You have entered an invalid email address!");
document.myform.email.focus();
return false;
}


return true;
}

</script>

</head>
<body>
<form name="myform"  action="submit.php" method="post"  onsubmit="return(valid());" >
Name <input type="text" name="name"  >
contact<input type="text" name="contact">
city<input type=text   name="city">
email<input type=text name="email">
address<input type=text name="address"">
<input   type=submit     name=submit>
</form>
</body>
</html>

------------------------------------------------------------------------------------------------------------------------
(23)Slide    Show  code  Example in javascript  :

<script type="text/javascript">
var i = 0;
var image = new Array();  
// LIST OF IMAGES
image[0] = "php_img.png";
image[1] = "domain.jpg";
image[2] = "1.png";  
image[3]="2.jpg";
var k = image.length-1;   

var caption = new Array();

// LIST OF CAPTİONS 
caption[0] = "Caption for the first image";
caption[1] = "Caption for the second image";
caption[2] = "Caption for the third image";  

function swapImage(){
var el = document.getElementById("mydiv");
el.innerHTML=caption[i];
var img= document.getElementById("slide");
img.src= image[i]; 
if(i < k ) { i++;} 
else  { i = 0; }
setTimeout("swapImage()",5000); 
}

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}
else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();}}} 
addLoadEvent(function() {
swapImage(); }); 
</script>

<table style="border:3px solid #00aaff;background-color:#00aaaa;">
<tr>
<td>
<img name="slide" id="slide" alt ="my images" height="285" width="485" src="php_img.png"/>
</td>

</tr>
<tr>
<td align="center"style="font:small-caps bold 15px georgia; color:blue;">
<div id ="mydiv"></div>
</tr>
</td>
</table>

(24)zoom in & zoom out  javascript code onMouseover & onMouesout example:

<html>
<BODY>
<script>
var nW,nH,oH,oW;
function zoomToggle(iWideSmall,iHighSmall,iWideLarge,iHighLarge,whichImage)
{
oW=whichImage.style.width;oH=whichImage.style.height;
if((oW==iWideLarge)||(oH==iHighLarge))
    {

    nW=iWideSmall;
    nH=iHighSmall;
    }
else
    {

    nW=iWideLarge;
    nH=iHighLarge;
    }

whichImage.style.width=nW;
whichImage.style.height=nH;
}
</script>
<table >
 <tr>
 <td >      
 <img border="0"  src="1.png" width="100" height="100" onMouseOut="zoomToggle('100px','100px','200px','200px',this);"  onMouseOver="zoomToggle('300px','300px','400px','400px',this);">
 <br>
 </td>
 </tr>
 </table>
</body>
</html>

(25)Gallery  Code example in  Javascript :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Simple Photo Gallery with HTML and JavaScript</title>

<style type="text/css">
body {
background: #222;
margin: 0;
}
.thumbnails img {
height: 80px;
border: 4px solid #555;
padding: 1px;
margin: 0 10px 10px 0;
}

.thumbnails img:hover {
border: 4px solid #00ccff;
cursor:pointer;
}

.preview img {
border: 4px solid #444;
padding: 1px;
width: 800px;
}
</style>
</head>

<body>
<div class="gallery" align="center">
<h3>Simple HTML Photo Gallery with JavaScript</h3>

<div class="thumbnails">
<img onmouseover="preview.src=img1.src" name="img1" src="1.png" alt="" />
<img onmouseover="preview.src=img2.src" name="img2" src="php_img.png" alt="" />
<img onmouseover="preview.src=img3.src" name="img3" src="2.jpg" alt="" />
<img onmouseover="preview.src=img4.src" name="img4" src="images/img4.jpg" alt="" />
<img onmouseover="preview.src=img5.src" name="img5" src="images/img5.jpg" alt="" />
</div>
<div class="preview" align="center">
<img name="preview" src="1.png" alt=""/>
</div>

</div> <!-- Close the gallery div -->
</body>
</html>


(26)simple calculator in Javascript:

<FORM NAME="Calc">
<TABLE BORDER=4>
<TR>
<TD>
<INPUT TYPE="text"   NAME="Input" Size="16">
<br>
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE="button" NAME="one"   VALUE="  1  " OnClick="Calc.Input.value += '1'">
<INPUT TYPE="button" NAME="two"   VALUE="  2  " OnCLick="Calc.Input.value += '2'">
<INPUT TYPE="button" NAME="three" VALUE="  3  " OnClick="Calc.Input.value += '3'">
<INPUT TYPE="button" NAME="plus"  VALUE="  +  " OnClick="Calc.Input.value += ' + '">
<br>
<INPUT TYPE="button" NAME="four"  VALUE="  4  " OnClick="Calc.Input.value += '4'">
<INPUT TYPE="button" NAME="five"  VALUE="  5  " OnCLick="Calc.Input.value += '5'">
<INPUT TYPE="button" NAME="six"   VALUE="  6  " OnClick="Calc.Input.value += '6'">
<INPUT TYPE="button" NAME="minus" VALUE="  -  " OnClick="Calc.Input.value += ' - '">
<br>
<INPUT TYPE="button" NAME="seven" VALUE="  7  " OnClick="Calc.Input.value += '7'">
<INPUT TYPE="button" NAME="eight" VALUE="  8  " OnCLick="Calc.Input.value += '8'">
<INPUT TYPE="button" NAME="nine"  VALUE="  9  " OnClick="Calc.Input.value += '9'">
<INPUT TYPE="button" NAME="times" VALUE="  x  " OnClick="Calc.Input.value += ' * '">
<br>
<INPUT TYPE="button" NAME="clear" VALUE="  C  " OnClick="Calc.Input.value = ''">
<INPUT TYPE="button" NAME="zero"  VALUE="  0  " OnClick="Calc.Input.value += '0'">
<INPUT TYPE="button" NAME="DoIt"  VALUE="  =  " OnClick="Calc.Input.value = eval(Calc.Input.value)">
<INPUT TYPE="button" NAME="div"   VALUE="  /  " OnClick="Calc.Input.value += ' / '">
<br>
</TD>
</TR>
</TABLE>
</FORM>
--------------------------------------------------------------------------------------------------------------------------

(27)Scientific  Calculator code in javascript   save given code as  cal.html & open it with any browser:

<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
function addChar(input, character) {
if(input.value == null || input.value == "0")
input.value = character
else
input.value += character
}

function cos(form) {
form.display.value = Math.cos(form.display.value);
}

function sin(form) {
form.display.value = Math.sin(form.display.value);
}

function tan(form) {
form.display.value = Math.tan(form.display.value);
}

function sqrt(form) {
form.display.value = Math.sqrt(form.display.value);
}

function ln(form) {
form.display.value = Math.log(form.display.value);
}

function exp(form) {
form.display.value = Math.exp(form.display.value);
}

function deleteChar(input) {
input.value = input.value.substring(0, input.value.length - 1)
}

function changeSign(input) {
if(input.value.substring(0, 1) == "-")
input.value = input.value.substring(1, input.value.length)
else
input.value = "-" + input.value
}

function compute(form) {
form.display.value = eval(form.display.value)
}

function square(form) {
form.display.value = eval(form.display.value) * eval(form.display.value)
}

function checkNum(str) {
for (var i = 0; i < str.length; i++) {
var ch = str.substring(i, i+1)
if (ch < "0" || ch > "9") {
if (ch != "/" && ch != "*" && ch != "+" && ch != "-" && ch != "."
&& ch != "(" && ch!= ")") {
alert("invalid entry!")
return false
}
}
}
return true
}
</SCRIPT>
</head>
<body>
<FORM NAME="sci-calc">
<TABLE CELLSPACING="0" CELLPADDING="1">
<TR>
<TD COLSPAN="5" ALIGN="center"><INPUT NAME="display" VALUE="0" SIZE="28" MAXLENGTH="25"></TD>
</TR>
<TR>
<TD ALIGN="center"><INPUT TYPE="button" VALUE=" exp " ONCLICK="if (checkNum(this.form.display.value)) { exp(this.form) }"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  7  " ONCLICK="addChar(this.form.display, '7')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  8  " ONCLICK="addChar(this.form.display, '8')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  9  " ONCLICK="addChar(this.form.display, '9')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="   /   " ONCLICK="addChar(this.form.display, '/')"></TD>
</TR>
<TR>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="   ln   " ONCLICK="if (checkNum(this.form.display.value)) { ln(this.form) }"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  4  " ONCLICK="addChar(this.form.display, '4')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  5  " ONCLICK="addChar(this.form.display, '5')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  6  " ONCLICK="addChar(this.form.display, '6')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="   *   " ONCLICK="addChar(this.form.display, '*')"></TD>
</TR>
<TR>
<TD ALIGN="center"><INPUT TYPE="button" VALUE=" sqrt " ONCLICK="if (checkNum(this.form.display.value)) { sqrt(this.form) }"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  1  " ONCLICK="addChar(this.form.display, '1')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  2  " ONCLICK="addChar(this.form.display, '2')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  3  " ONCLICK="addChar(this.form.display, '3')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="   -   " ONCLICK="addChar(this.form.display, '-')"></TD>
</TR>
<TR>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  sq  " ONCLICK="if (checkNum(this.form.display.value)) { square(this.form) }"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="  0  " ONCLICK="addChar(this.form.display, '0')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="   .  " ONCLICK="addChar(this.form.display, '.')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE=" +/- " ONCLICK="changeSign(this.form.display)"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="   +  " ONCLICK="addChar(this.form.display, '+')"></TD>
</TR>
<TR>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="    (    " ONCLICK="addChar(this.form.display, '(')"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="cos" ONCLICK="if (checkNum(this.form.display.value)) { cos(this.form) }"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE=" sin" ONCLICK="if (checkNum(this.form.display.value)) { sin(this.form) }"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE=" tan" ONCLICK="if (checkNum(this.form.display.value)) { tan(this.form) }"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="   )   " ONCLICK="addChar(this.form.display, ')')"></TD>
</TR>
<TR>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="clear" ONCLICK="this.form.display.value = 0 "></TD>
<TD ALIGN="center" COLSPAN="3"><INPUT TYPE="button" VALUE="backspace" ONCLICK="deleteChar(this.form.display)"></TD>
<TD ALIGN="center"><INPUT TYPE="button" VALUE="enter" NAME="enter" ONCLICK="if (checkNum(this.form.display.value)) { compute(this.form) }"></TD>
</TR>
</TABLE>
</FORM>
</body>

</html>

--------------------------------------------------------------------------------------------------------------------------

(28) TOuch Screen  pad using html ,css & javascript for Android ,IOS  mobile device:


<html>
<head>
<title>Sketchpad</title>

<script type="text/javascript">
    // Variables for referencing the canvas and 2dcanvas context
    var canvas,ctx;

    // Variables to keep track of the mouse position and left-button status 
    var mouseX,mouseY,mouseDown=0;

    // Variables to keep track of the touch position
    var touchX,touchY;

    // Draws a dot at a specific position on the supplied canvas name
    // Parameters are: A canvas context, the x position, the y position, the size of the dot
    function drawDot(ctx,x,y,size) {
        // Let's use black by setting RGB values to 0, and 255 alpha (completely opaque)
        r=0; g=0; b=0; a=255;

        // Select a fill style
        ctx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";

        // Draw a filled circle
        ctx.beginPath();
        ctx.arc(x, y, size, 0, Math.PI*2, true); 
        ctx.closePath();
        ctx.fill();
    } 

    // Clear the canvas context using the canvas width and height
    function clearCanvas(canvas,ctx) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }

    // Keep track of the mouse button being pressed and draw a dot at current location
    function sketchpad_mouseDown() {
        mouseDown=1;
        drawDot(ctx,mouseX,mouseY,12);
    }

    // Keep track of the mouse button being released
    function sketchpad_mouseUp() {
        mouseDown=0;
    }

    // Keep track of the mouse position and draw a dot if mouse button is currently pressed
    function sketchpad_mouseMove(e) { 
        // Update the mouse co-ordinates when moved
        getMousePos(e);

        // Draw a dot if the mouse button is currently being pressed
        if (mouseDown==1) {
            drawDot(ctx,mouseX,mouseY,12);
        }
    }

    // Get the current mouse position relative to the top-left of the canvas
    function getMousePos(e) {
        if (!e)
            var e = event;

        if (e.offsetX) {
            mouseX = e.offsetX;
            mouseY = e.offsetY;
        }
        else if (e.layerX) {
            mouseX = e.layerX;
            mouseY = e.layerY;
        }
     }

    // Draw something when a touch start is detected
    function sketchpad_touchStart() {
        // Update the touch co-ordinates
        getTouchPos();

        drawDot(ctx,touchX,touchY,12);

        // Prevents an additional mousedown event being triggered
        event.preventDefault();
    }

    // Draw something and prevent the default scrolling when touch movement is detected
    function sketchpad_touchMove(e) { 
        // Update the touch co-ordinates
        getTouchPos(e);

        // During a touchmove event, unlike a mousemove event, we don't need to check if the touch is engaged, since there will always be contact with the screen by definition.
        drawDot(ctx,touchX,touchY,12); 

        // Prevent a scrolling action as a result of this touchmove triggering.
        event.preventDefault();
    }

    // Get the touch position relative to the top-left of the canvas
    // When we get the raw values of pageX and pageY below, they take into account the scrolling on the page
    // but not the position relative to our target div. We'll adjust them using "target.offsetLeft" and
    // "target.offsetTop" to get the correct values in relation to the top left of the canvas.
    function getTouchPos(e) {
        if (!e)
            var e = event;

        if(e.touches) {
            if (e.touches.length == 1) { // Only deal with one finger
                var touch = e.touches[0]; // Get the information for finger #1
                touchX=touch.pageX-touch.target.offsetLeft;
                touchY=touch.pageY-touch.target.offsetTop;
            }
        }
    }


    // Set-up the canvas and add our event handlers after the page has loaded
    function init() {
        // Get the specific canvas element from the HTML document
        canvas = document.getElementById('sketchpad');

        // If the browser supports the canvas tag, get the 2d drawing context for this canvas
        if (canvas.getContext)
            ctx = canvas.getContext('2d');

        // Check that we have a valid context to draw on/with before adding event handlers
        if (ctx) {
            // React to mouse events on the canvas, and mouseup on the entire document
            canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
            canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
            window.addEventListener('mouseup', sketchpad_mouseUp, false);

            // React to touch events on the canvas
            canvas.addEventListener('touchstart', sketchpad_touchStart, false);
            canvas.addEventListener('touchmove', sketchpad_touchMove, false);
        }
    }
</script>

<style>
/* Some CSS styling */
#sketchpadapp {
    /* Prevent nearby text being highlighted when accidentally dragging mouse outside confines of the canvas */
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.leftside {
    float:left;
    width:220px;
    height:285px;
    background-color:#def;
    padding:10px;
    border-radius:4px;
}
.rightside {
    float:left;
    margin-left:10px;
}
#sketchpad {
    float:left;
    height:300px;
    width:400px;
    border:2px solid #888;
    border-radius:4px;
    position:relative; /* Necessary for correct mouse co-ords in Firefox */
}
#clearbutton {
    font-size: 15px;
    padding: 10px;
    -webkit-appearance: none;
    background: #eee;
    border: 1px solid #888;
}
</style>
</head>

<body onload="init()">
    <div id="sketchpadapp">
        <div class="leftside">
             Touchscreen and mouse support HTML5 canvas sketchpad.<br/><br/>
             Draw something by tapping or dragging.<br/><br/>
             Works on iOS, Android and desktop/laptop touchscreens using Chrome/Firefox/Safari.<br/><br/>
             <input type="submit" value="Clear Sketchpad" id="clearbutton" onclick="clearCanvas(canvas,ctx);">
        </div>
        <div class="rightside">
            <canvas id="sketchpad" height="300" width="400">
            </canvas>
        </div>
    </div>
</body>

</html>

--------------------------------------------------------------------------------------------------------------------------(29)Form calculation with all elements of  form:



(1)first create js  file code    for “formcalculations.js”:
/*


You are free to use the code in Commercial or non-commercial projects
*/

 //Set up an associative array
 //The keys represent the size of the cake
 //The values represent the cost of the cake i.e A 10" cake cost's $35
 var cake_prices = new Array();
 cake_prices["Round6"]=20;
 cake_prices["Round8"]=25;
 cake_prices["Round10"]=35;
 cake_prices["Round12"]=75;

 //Set up an associative array
 //The keys represent the filling type
 //The value represents the cost of the filling i.e. Lemon filling is $5,Dobash filling is $9
 //We use this this array when the user selects a filling from the form
 var filling_prices= new Array();
 filling_prices["None"]=0;
 filling_prices["Lemon"]=5;
 filling_prices["Custard"]=5;
 filling_prices["Fudge"]=7;
 filling_prices["Mocha"]=8;
 filling_prices["Raspberry"]=10;
 filling_prices["Pineapple"]=5;
 filling_prices["Dobash"]=9;
 filling_prices["Mint"]=5;
 filling_prices["Cherry"]=5;
 filling_prices["Apricot"]=8;
 filling_prices["Buttercream"]=7;
 filling_prices["Chocolate Mousse"]=12;

                 
                 
// getCakeSizePrice() finds the price based on the size of the cake.
// Here, we need to take user's the selection from radio button selection
function getCakeSizePrice()
    var cakeSizePrice=0;
    //Get a reference to the form id="cakeform"
    var theForm = document.forms["cakeform"];
    //Get a reference to the cake the user Chooses name=selectedCake":
    var selectedCake = theForm.elements["selectedcake"];
    //Here since there are 4 radio buttons selectedCake.length = 4
    //We loop through each radio buttons
    for(var i = 0; i < selectedCake.length; i++)
    {
        //if the radio button is checked
        if(selectedCake[i].checked)
        {
            //we set cakeSizePrice to the value of the selected radio button
            //i.e. if the user choose the 8" cake we set it to 25
            //by using the cake_prices array
            //We get the selected Items value
            //For example cake_prices["Round8".value]"
            cakeSizePrice = cake_prices[selectedCake[i].value];
            //If we get a match then we break out of this loop
            //No reason to continue if we get a match
            break;
        }
    }
    //We return the cakeSizePrice
    return cakeSizePrice;
}

//This function finds the filling price based on the
//drop down selection
function getFillingPrice()
{
    var cakeFillingPrice=0;
    //Get a reference to the form id="cakeform"
    var theForm = document.forms["cakeform"];
    //Get a reference to the select id="filling"
     var selectedFilling = theForm.elements["filling"];
    
    //set cakeFilling Price equal to value user chose
    //For example filling_prices["Lemon".value] would be equal to 5
    cakeFillingPrice = filling_prices[selectedFilling.value];

    //finally we return cakeFillingPrice
    return cakeFillingPrice;
}

//candlesPrice() finds the candles price based on a check box selection
function candlesPrice()
{
    var candlePrice=0;
    //Get a reference to the form id="cakeform"
    var theForm = document.forms["cakeform"];
    //Get a reference to the checkbox id="includecandles"
    var includeCandles = theForm.elements["includecandles"];

    //If they checked the box set candlePrice to 5
    if(includeCandles.checked==true)
    {
        candlePrice=5;
    }
    //finally we return the candlePrice
    return candlePrice;
}

function insciptionPrice()
{
    //This local variable will be used to decide whether or not to charge for the inscription
    //If the user checked the box this value will be 20
    //otherwise it will remain at 0
    var inscriptionPrice=0;
    //Get a refernce to the form id="cakeform"
    var theForm = document.forms["cakeform"];
    //Get a reference to the checkbox id="includeinscription"
    var includeInscription = theForm.elements["includeinscription"];
    //If they checked the box set inscriptionPrice to 20
    if(includeInscription.checked==true){
        inscriptionPrice=20;
    }
    //finally we return the inscriptionPrice
    return inscriptionPrice;
}
       
function calculateTotal()
{
    //Here we get the total price by calling our function
    //Each function returns a number so by calling them we add the values they return together
    var cakePrice = getCakeSizePrice() + getFillingPrice() + candlesPrice() + insciptionPrice();
   
    //display the result
    var divobj = document.getElementById('totalPrice');
    divobj.style.display='block';
    divobj.innerHTML = "Total Price For the Cake $"+cakePrice;

}

function hideTotal()
{
    var divobj = document.getElementById('totalPrice');
    divobj.style.display='none';
}









(2)second made code for  css  file “cakeform.css”   :


#wrap{
                width:400px;
                margin:0 auto;
                text-align:left;
                margin-top:8px;
                padding:5px;
                background:#fff;
    font-family:AvenirLTStd, Arial, Helvetica, sans-serif;
                font-size:13px;   
    line-height:16px;
}
#wrap .cont_details fieldset,.cont_order fieldset{
                margin:10px;
                padding:20px;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    -khtml-border-radius: 10px;
    border-radius: 10px;
}
#wrap legend{
                font-size:16px;
                font-family:Georgia, "Times New Roman", Times, serif;
                color:#000;
                font-weight:bold;
                font-style:italic;
    padding-bottom:10px;
}
#wrap .cont_details input{
                margin-bottom:10px;
                color:#000;
}
#wrap .input1:hover,.input1:active{
               
}
#wrap label{
                display:block;
                font-size:12px;
                color:#000;
    font-weight:bold;
}
#wrap label.inlinelabel
{
    display:inline;
}
#wrap .cont_order input{
                margin-bottom:5px;
}
#wrap .cont_order p{
                padding-top:5px;
}

#wrap input[type="radio"]
{
margin-top:8px;
margin-bottom:8px;
}

#wrap input[type="text"]:hover,
#wrap input[type="text"]:active {
background-color: #FAF398;
}

#wrap input#submit
{
margin:10px;
padding-left:20px;
padding-right:20px;
padding-top:10px;
padding-bottom:10px;
}

#wrap div#totalPrice
{
    padding:10px;
    font-weight:bold;
    background-color:#ff0;
}

#wrap label.radiolabel
{
font-weight:normal;
 display:inline;
}

(3)Now finally write code for   formcal.html :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
    <title>calcluation trick by om</title>
    <script type="text/javascript" src="formcalculations.js"></script>
    <link href="cakeform.css" rel="stylesheet" type="text/css" />
</head>
<body onload='hideTotal()'>
    <div id="wrap">
        <form action="" id="cakeform" onsubmit="return false;">
        <div>
            <div class="cont_order">
               <fieldset>
                <legend>Make your cake!</legend>
                <label >Size Of the Cake</label>
                <label class='radiolabel'><input type="radio"  name="selectedcake" value="Round6" onclick="calculateTotal()" />Round cake 6" -  serves 8 people ($20)</label><br/>
                <label class='radiolabel'><input type="radio"  name="selectedcake" value="Round8" onclick="calculateTotal()" />Round cake 8" - serves 12 people ($25)</label><br/>
                <label class='radiolabel'><input type="radio"  name="selectedcake" value="Round10" onclick="calculateTotal()" />Round cake 10" - serves 16 people($35)</label><br/>
                <label class='radiolabel'><input type="radio"  name="selectedcake" value="Round12" onclick="calculateTotal()" />Round cake 12" - serves 30 people($75)</label><br/>
                <br/>
                <label >Filling</label>
        
                <select id="filling" name='filling' onchange="calculateTotal()">
                <option value="None">Select Filling</option>
                <option value="Lemon">Lemon($5)</option>
                <option value="Custard">Custard($5)</option>
                <option value="Fudge">Fudge($7)</option>
                <option value="Mocha">Mocha($8)</option>
                <option value="Raspberry">Raspberry($10)</option>
                <option value="Pineapple">Pineapple($5)</option>
                <option value="Dobash">Dobash($9)</option>
                <option value="Mint">Mint($5)</option>
                <option value="Cherry">Cherry($5)</option>
                <option value="Apricot">Apricot($8)</option>
                <option value="Buttercream">Buttercream($7)</option>
                <option value="Chocolate Mousse">Chocolate Mousse($12)</option>
               </select>
                <br/>
                <p>
                <label for='includecandles' class="inlinelabel">Include Candles($5)</label>
               <input type="checkbox" id="includecandles" name='includecandles' onclick="calculateTotal()" />
               </p>
              
                <p>
                <label class="inlinelabel" for='includeinscription'>Include Inscription($20)</label>
                <input type="checkbox" id="includeinscription" name="includeinscription" onclick="calculateTotal()" />
                <input type="text"  id="theinscription" name="theinscription" value="Enter Inscription"  />
                </p>
                <div id="totalPrice"></div>
               
                </fieldset>
            </div>
           
                <div class="cont_details">
                <fieldset>
                <legend>Contact Details</legend>
                <label for='name'>Name</label>
                <input type="text" id="name" name='name' />
                <br/>
                <label for='address'>Address</label>
                <input type="text" id="address" name='address' />
                <br/>
                <label for='phonenumber'>Phone Number</label>
                <input type="text"  id="phonenumber" name='phonenumber'/>
                <br/>
                </fieldset>
            </div>
            <input type='submit' id='submit' value='Submit' onclick="calculateTotal()" />
        </div> 
       </form>
                </div><!--End of wrap-->

</body>
</html>




Previous
Next Post »