Emil Dohne Emil Dohne - 8 months ago 39
Javascript Question

Make Math.max.apply read variables

I am fairly new to coding and tried something for fun, however I am struggling with it

function result() {
var n1 = document.getElementById("N1");
var n2 = document.getElementById("N2");
var n3 = document.getElementById("N3");
var a = [n1,n2,n3];
var temp = Math.max.apply(Math, a)
var out=document.getElementById("res").innerHTML = temp;

I am trying to make it output the numbers that are being input through HTML

<td><input class="textBox" id="N3" type="number"/></td>

However it wont read it as number and will just display NaN. Help would be appreciated.


If you need temp to be the highest value entered, the following will work:

function result() {
    document.getElementById("res").innerHTML = Math.max(
        parseFloat( document.getElementById("N1").value ),
        parseFloat( document.getElementById("N2").value ),
        parseFloat( document.getElementById("N3").value )

Some comments:

  • Notice that we simply use Math.max(). apply() is not needed here, since you're explicitly calling the max() method.
  • I'm assuming that N1, N2, etc. are <input /> elements, so you need to get their value attribute using .value.
  • We need to treat the values from the inputs as floats (or integers if that works), so we use parseFloat() (or parseInt() respectively). This isn't technically required in most modern browsers, but is good practice nevertheless.