1

< script type = "text/javascript" >
  function myFunction() {
    var n1 = document.getElementById("form-control1").innerHTML;
    var n2 = document.getElementById("form-control2").innerHTML;

    return Math.max(n1, n2);
  };
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>JavaScript Challenge</title>


</head>

<body>
<!-- user interface -->
  First number
  <input type="text" id="form-control1" placeholder="your first number">Second number
  <input type="text" id="form-control2" placeholder="your second number">
  <br>
  <br>
  <button onclick="myFunction()">Calculate</button>

  </script>

</body>

</html>

I would like the user input value to be assigned on the variable n1 and n2. After that when the button is clicked the variable with the max value is shown up on the webpage. but at the moment the value does not seem to be stored as it says undefined. what can i do? any help Thanks in advance

theberoman
  • 11
  • 3

2 Answers2

0

Convert the innerHTML string into an integer:

return Math.max(parseInt(n1),parseInt(n2));
Justice
  • 290
  • 2
  • 7
  • You don't need to do this. `Math.max` handles string arguments just fine. The same applies if he is taking the `value` property of the `input` element as he should instead of using `innerHTML`. –  Oct 27 '15 at 04:05
0

Try substituting .value for .innerHTML at input elements to retrieve value of input element; create array containing n1, n2 , converting to values to Number using Array.prototype.map() , adding output element to print result of Math.max to document

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>JavaScript Challenge</title>
</head>
<body>
  <!-- user interface -->
  First number
  <input type="text" id="form-control1" placeholder="your first number">Second number
  <input type="text" id="form-control2" placeholder="your second number">
  <output></output>
  <br>
  <br>
  <button onclick="myFunction()">Calculate</button>
  <script type="text/javascript">
    function myFunction() {
      var n1 = document.getElementById("form-control1").value;
      var n2 = document.getElementById("form-control2").value;
      document.querySelector("output").innerHTML = Math.max.apply(Math, [n1, n2]);
    };
  </script>
</body>
</html>
guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    The `.map(Number)` is unnecessary, since `Math.max` handles string arguments. –  Oct 27 '15 at 04:06