I am trying to sort the number in descending order using javascript. It works well for strings but when I use numbers it gives me wrong results.
Following is the code:
<html>
<head>
<script language ="Javascript">
function sort(form)
{
var a1=form.first.value
var b1 = form.second.value
var c1 =form.third.value
var a2= parseFloat(a1)
var b2=parseFloat(b1)
var c2= parseFloat(c1)
var rank_the_numbers = [a2,b2,c2]
rank_the_numbers.sort(function(a, b){return a-b})
document.writeln("The largest number is: "+rank_the_numbers[0])
document.writeln("<br> The second largest number is: " +rank_the_numbers[1])
document.writeln("<br> The smallest number is: " +rank_the_numbers[2])
document.writeln(rank_the_numbers)
}
</script>
</head>
<form onSubmit="return sort(this)">
Enter any three numbers: <br>
<input type="text" name="first" size=5><br>
<input type="text" name="second"size=5><br>
<input type="text" name="third" size=5><br>
<input type="submit" value= "Rank the numbers!" onClick = "sort(this.form)">
</form>
</body>
</html>
What changes should i make so that the code runs correctly for the numbers too. I went through a few articles on stackoverflow and used (function(a, b){return a-b}), but it too did not work.