Mibby Mibby - 1 month ago 20
Javascript Question

Determine Min Max

Past 10 it will make the minimum the 10 and say the 6 the maximum aside from the number "1". I'm not sure why and if someone can let me know or push me towards the answer that would be great.




function btnMinMax_onclick()
{
// assign textbox elements to variables for easier access
var firstTextbox = document.getElementById("txtNum1");
var secondTextbox = document.getElementById("txtNum2");
var minTextbox = document.getElementById("txtMin");
var maxTextbox = document.getElementById("txtMax");

var num1 = firstTextbox.value;
var num2 = secondTextbox.value;

var isMin = determineMinimum(num1, num2);
var isMax = determineMaximum(num1, num2);

minTextbox.value = isMin;
maxTextbox.value = isMax;
}

function determineMinimum(number1, number2)
{
if (number1 < number2){
return number1;
} else {
return number2;
}
}

function determineMaximum(number1, number2)
{
if (number2 > number1){
return number2;
} else {
return number1;
}
}

Answer

The values you're pulling from the text boxes are String, not Number. You need to convert explicitly or it will order lexicographically, not numerically.

Simplest solution is to change:

var num1 = firstTextbox.value;
var num2 = secondTextbox.value;

to:

var num1 = parseInt(firstTextbox.value, 10);
var num2 = parseInt(secondTextbox.value, 10);

so you have real integer values, not strings that look like integers. Use parseFloat instead if you need to accept non-integer values (e.g. 3.14).