Function call in JavaScript

In JavaScript after the function is defined or implemented, it can be called by placing the name of the function before parentheses.
Example.
<html>
<head>
<title>Call function</title>
<script type="text/javascript">

function cal(){ //define cal function
var val1=prompt("Enter value 1:");
var val2=prompt("Enter value 2");
var res=eval(val1)+eval(val2);
alert(res);
}

cal(); //call the cal function

</script>

</head>
<body>

</body>
</html>

You also can call the function when an event occurs on the page. For example, if you want to call the sum function when the button is clicked, you can assign the sum function to the onclick event of the button control.
Example:

<html>
<head>
<title>Call function</title>
<script type="text/javascript">
function sum(){
var val1=document.getElementById("txtval1").value;
var val2=document.getElementById("txtval2").value;
var result=eval(val1)+eval(val2);
alert("Result: "+ result);
}

</script>

</head>
<body>

<form action="#">
<table>
<tr>
<td>Enter value:</td><td> <input type="text" id="txtval1" ></td>
</tr>
<tr>
<td>Enter another value: </td><td><input type="text" id="txtval2" ></td>
</tr>
<tr>
<td><input type="button" name="submit" value="Sum" onclick="sum()"></td>
</tr>
</table>
</form>

</body>
</html>

If the function has parameters you need to provide the parameter values when it is called.
Example:
<html>
<head>
<title>Call function with parameter values</title>
<script type="text/javascript">

function cal(val1,val2){ //define cal function with val1 and val2 parameters
var res=eval(val1)+eval(val2);
alert("Result:"+res);
}

cal(23,34); //call the cal function and at the same time values are passed to the function throught parameters

</script>

</head>
<body>

</body>
</html>

Posted by: Lavy | post date: 03-26-2013 | Subject: JavaScript




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.