How tags communicate with each other?

To provide the communication among the tags, we need to give some identification to the tags using ID attribute.

Example

<input type="text" id="num">
<input type="text" id="result">

To communicate with a tag, we need to get reference of it inside memory using getElementById() function of document object

Use var keyword to define the variables to get reference of the tags

Example

var x=document.getElementById("num");
var y=document.getElementById("result");

Now we can use the value property to read the data or write the data

Note: All the values received from the input tags are of string type. If we want to do some numerical calculation on the data, we need to convert the string data to numeric data using data conversion functions parseInt() and parseFloat()

Example

var n=parseInt(x.value);

Sample Case

Create a web page having two text boxes, first one to input a number and second one to show a result. Create a button having text as factorial. On Click on the button show the factorial of given number in result text box.

<!DOCTYPE html>
<html>
    <head>
        <script>
            function factorial(){
                var n=parseInt(document.getElementById("num").value);
                var f=1;
                for(i=1;i<=n;i++)
                    f=f*i;
                document.getElementById("result").value=f;
            }
        </script>
    </head>
    <body>
        Number <input type="text" id="num"><br>
        Result <input type="text" id="result"><br>
        <input type="button" value="Factorial" onClick="factorial()">
    </body>
</html>

Assignment

Create a web page having two text boxes to input two numbers.
Create for buttons for + - * and /
On click on the buttons show the result in a dialog

<!DOCTYPE html>
<html>
    <head>
        <script>
            function result(opr){
                var x=parseFloat(document.getElementById("num1").value);
                var y=parseFloat(document.getElementById("num2").value);
                switch(opr){
                    case '+': alert("Addition is " + (x+y));break;
                    case '-': alert("Subtraction is " + (x-y));break;
                    case '*': alert("Product is " + (x*y));break;
                    case '/': alert("Division is " + (x/y));break;
                }
            }
        </script>
    </head>
    <body>
        Number 1 <input type="number" id="num1"><br>
        Number 2 <input type="number" id="num2"><br>
        <input type="button" value="+" onclick="result('+')">
        <input type="button" value="-" onclick="result('-')">
        <input type="button" value="*" onclick="result('*')">
        <input type="button" value="/" onclick="result('/')">
    </body>
</html>

Comments