JavaScript max method

If we have to compare some values then we can use the if-else statement but
it will make our code more complex. Therefore instead of using the if-else
statement we can use the max method of the Math object. It will compare zero or
more values and then will return the resulted maximum value as a returning
value.
Syntax:
| Math.max( firstValue, secondValue, thirdValue,
..........nValue); |
This max() method can be used to find maximum of zero or more values and it
returns the value "infinity" if no argument is passed.
Description of code:
In the following code we have created two text input boxes and we have taken
both values from the user for getting the maximum of it. On button click "Find Max of
both" it calls the function findMax() as we have defined in
the JavaScript of our code. It finds the maximum of both the values and shows
the result in the alert() method. Here is the example code :
<html>
<body>
<script type="text/javascript">
function findMax(){
var val1 = document.getElementById('txt1').value;
var val2 = document.getElementById('txt2').value;
alert("Maximum of "+val1+" and " +val2+" is :"+Math.max(val1,val2));
}
</script>
<div align="center">
<center>
<table border="0" cellpadding="0" cellspacing="0" width="60%" bgcolor="#800080">
<tr>
<td width="100%">
<p align="center"><font color="#FFFFFF" size="7" face="Comic Sans MS">max
method</font></td>
</tr>
</table>
</center>
</div>
<div align="center">
<center>
<table border="0" cellpadding="0" cellspacing="0" width="60%">
<tr>
<td width="50%" align="right">Insert first value</td>
<td width="50%">
<input type="text" id="txt1" value=""/>
</td>
</tr>
<tr>
<td width="50%" align="right">Insert second value</td>
<td width="50%"><input type="text" id="txt2" value=""/>
</td>
</tr>
<tr>
<td width="50%"></td>
<td width="50%">
<input type="button" onclick="findMax();"
value="Find Max of both" />
</td>
</tr>
</table>
</center>
</div>
</body>
</html> |
Output :

Insert two values to find max of them.

You can also download full source code from the following link.
Download Source Code

|