JavaScript min method
As we can use the Math.max() method to find the maximum of zero or more values in the same way we can use Math.min() method to find the minimum of zero or more values. In this example code we are finding the minimum value between the two values. Syntax for the using Math.min() method is as follows:
Syntax:
Math.min( firstValue, secondValue, thirdValue, ..........nValue); |
This min() method can be used to find minimum 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 minimum of it. On button click "Find Minimum of both" it calls the function findMinimum() as we have defined in the JavaScript of our code. It finds the minimum between both the values and shows the result in the alert() method. Here is the example code :
<html> <body> <script type="text/javascript"> function findMinimum(){ var val1 = document.getElementById('txt1').value; var val2 = document.getElementById('txt2').value; alert("Minimum of "+val1+" and " +val2+" is :"+Math.min(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"> min 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="findMinimum();" value="Find Minimum of both" /> </td> </tr> </table> </center> </div> </body> </html> |
Output :
Insert two values to find minimum of these.
You can also download full source code from the following link.