user2398355
user2398355

Reputation:

Simple JavaScript code for maximum and minimum not working

I am getting crazy, trying to understand what is wrong in this very simple piece of code in JS:

   <html>
   <head>
   <script type="text/JavaScript"> 
   conta=0;
   function numero()
        {
        var num= document.getElementById("n").value;
        if(conta==0)
           {
            min= num;
            mas=num;
            }

        if(mas<num)
          {
          mas= num;
          }

        if(min>num)
          {
          min=num;
          }
        conta++;
        document.getElementById("massimo").value= mas;
        document.getElementById("minimo").value= min;
        document.getElementById("conta").value= conta;
        }
    </script>
    </head>
    <body>

    <form>
    Valore: <input id="n" type="text"> <input value="Inserisci" onclick="numero()" type="button">
    <br>
    Massimo: <input id="massimo" type="text"> Minimo: <input id="minimo" type="text"> Contatore: <input id="conta" type="text">
    </form>
    </body>
    </html>

It should be quite straightforward: you put your number in the input text with id="n" and then click on a button calling numero() function. The problem is that it doesn't work! For example if I digit first the number 33 and then the number 6, number 6 is considered a maximum!

It seems that the instruction if (mas

I am pretty sure there is some very stupid error, but I am not able to spot it. Thanks a lot to everybody for help!

Giancarlo - Italy

Upvotes: 1

Views: 52

Answers (2)

Johann Echavarria
Johann Echavarria

Reputation: 9955

You can use parseInt, parseFloat and also just prefix the vars with a plus (+) symbol. Note that you can use Math.max() and Math.min(). Example:

Math.min(2, 6); /*returns 2*/
Math.min(1, 2, 6, 9, 20) ; /*returns 1*/

Also if you have the values in an array you can use these functions using Function.prototype.apply():

Math.min.apply(null, [3,5,8,9,30]); /*returns 3*/

Upvotes: 1

Andy Gaskell
Andy Gaskell

Reputation: 31761

You need to convert the values to numbers when you read them. If you need integers use parseInt if you need to support floats, use parseFloat.

function numero()
{
  var num= parseInt(document.getElementById("n").value, 10);
  if(conta==0)
  {
    min= num;
    mas=num;
  }
  if(mas<num)
  {
    mas= num;
  }
  if(min>num)
  {
    min=num;
  }
  conta++;
  document.getElementById("massimo").value= mas;
  document.getElementById("minimo").value= min;
  document.getElementById("conta").value= conta;
}

Upvotes: 2

Related Questions