Posted by : Sudhir Chekuri Sunday, 27 October 2013

Variables are used to hold the data retrieved from input controls.

In the below example a textbox and a button is displayed on the output screen. The text entered in the textbox is displayed in an alertbox when user clicks on the button.
In the below example txt1 is the id given to a textbox which is used to retreive its value using js code.
document.getElementById is used to find an item with id as txt1 in the html document.

Javascript code to display entered text in an alertbox

<html>
<head>
<script language="javascript">
function f1()
{
var a=document.getElementById("txt1").value;
alert(a);
}
</script>
</head>
<body>
<input type="text" id="txt1"/>
<input type="button" value="click me" onclick="f1()"/>
</body>
</html>



In the below example two textboxes and a button is displayed on the output screen. when user clicks on the button the added value of the two textboxes is displayed in an alert box.
parseInt is the function used to convert a value inside a variable into numeric type to perform arthimetic operations.

javascript code to add two numbers entered in two textboxes

<HTML>
<head>
<script language="javascript">
function f1()
{
var a=document.getElementById("txt1").value;
var b=document.getElementById("txt2").value;
var c=parseInt( a)+parseInt(b);
alert(c);
}
</script>

</head>
<body>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<button id="btn1" onclick="f1()" >
Click me
</button>
</body>
</html>


Comments

 //single line comments goes here
/* Multi line 
    comments in javascript
  */

Global variable: Variable that is created ouside the body of the function.
Local variable: Variable that is created inside the body of the function.

In the below example global variable "word" is created outside the function which can be called within and outside the function named "first".

Global variable example code:


<!DOCTYPE html>
<html>
  <head>
   
   <script type="text/javascript">
      var word="ABCD ";
      function first()
      {
     
        document.write("inside: "+word);
      }
   
       document.write("outside: "+word);
      first();
    </script>
   
  </head>
  <body>
  </body>
</html>

Output:

outside: ABCD inside: ABCD
------------------------

In the below example local variable "alphabet" is created inside the function which can be called within  the function named "first" only.

<!DOCTYPE html>
<html>

  <head>
   
   <script type="text/javascript">
   
      function first()
      {
        var alphabet="C ";
        document.write("inside: "+alphabet);
      }
   
      first();
    </script>
   
  </head>

  <body>
   
  </body>

</html>

Output:

inside: C

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Followers

Total Pageviews

Powered by Blogger.

Blog Archive

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -